pax_global_header00006660000000000000000000000064147104267470014526gustar00rootroot0000000000000052 comment=3df7872f1bf8e78cc484e642a6565a3489d0d710 vxgmichel-aioconsole-3df7872/000077500000000000000000000000001471042674700162135ustar00rootroot00000000000000vxgmichel-aioconsole-3df7872/.flake8000066400000000000000000000000361471042674700173650ustar00rootroot00000000000000[flake8] max-line-length = 88 vxgmichel-aioconsole-3df7872/.github/000077500000000000000000000000001471042674700175535ustar00rootroot00000000000000vxgmichel-aioconsole-3df7872/.github/workflows/000077500000000000000000000000001471042674700216105ustar00rootroot00000000000000vxgmichel-aioconsole-3df7872/.github/workflows/ci.yml000066400000000000000000000031671471042674700227350ustar00rootroot00000000000000name: CI on: push: pull_request: jobs: Quality: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: '3.11' - uses: pre-commit/action@v3.0.1 Tests: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13", "pypy-3.8", "pypy-3.9"] env: OS: ${{ matrix.os }} PYTHON: ${{ matrix.python-version }} steps: - uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Install test requirements run: pip install -e .[dev] - name: Run tests run: pytest - name: Upload coverage uses: codecov/codecov-action@v4 with: env_vars: OS,PYTHON token: ${{ secrets.CODECOV_TOKEN }} Release: runs-on: ubuntu-latest needs: [Quality, Tests] if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags') steps: - uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: 3.8 - name: Build wheel and source distribution run: | pip install build python -m build --sdist --wheel - name: Publish source package on PyPI uses: pypa/gh-action-pypi-publish@release/v1 with: user: __token__ password: ${{ secrets.pypi_password }} vxgmichel-aioconsole-3df7872/.gitignore000066400000000000000000000011201471042674700201750ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # Tempory files *~ # C extensions *.so # Distribution / packaging .Python env/ bin/ build/ _build/ develop-eggs/ dist/ eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg *.eggs # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .cache nosetests.xml coverage.xml .pytest_cache # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject # Rope .ropeproject # Django stuff: *.log *.pot # Sphinx documentation docs/_build/ vxgmichel-aioconsole-3df7872/.pre-commit-config.yaml000066400000000000000000000010251471042674700224720ustar00rootroot00000000000000repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v2.3.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/ambv/black rev: 24.10.0 hooks: - id: black language_version: python3 - repo: https://github.com/pycqa/flake8 rev: 7.0.0 hooks: - id: flake8 - repo: https://github.com/astral-sh/ruff-pre-commit # Ruff version. rev: v0.0.272 hooks: - id: ruff args: [ --fix, --exit-non-zero-on-fix] vxgmichel-aioconsole-3df7872/.readthedocs.yaml000066400000000000000000000003071471042674700214420ustar00rootroot00000000000000version: 2 build: os: ubuntu-22.04 tools: python: "3.11" python: install: - requirements: docs/requirements.txt - method: pip path: . sphinx: configuration: docs/conf.py vxgmichel-aioconsole-3df7872/LICENSE000066400000000000000000001044611471042674700172260ustar00rootroot00000000000000GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . vxgmichel-aioconsole-3df7872/MANIFEST.in000066400000000000000000000000321471042674700177440ustar00rootroot00000000000000include tests/conftest.py vxgmichel-aioconsole-3df7872/README.rst000066400000000000000000000110651471042674700177050ustar00rootroot00000000000000aioconsole ========== |docs-badge| |cov-badge| |ci-badge| |version-badge| |pyversion-badge| Asynchronous console and interfaces for asyncio aioconsole_ provides: * asynchronous equivalents to `input`_, `print`_, `exec`_ and `code.interact`_ * an interactive loop running the asynchronous python console * a way to customize and run command line interface using `argparse`_ * `stream`_ support to serve interfaces instead of using standard streams * the ``apython`` script to access asyncio code at runtime without modifying the sources Requirements ------------ * Python \>= 3.8 Installation ------------ aioconsole_ is available on PyPI_ and GitHub_. Both of the following commands install the ``aioconsole`` package and the ``apython`` script. .. code:: console $ pip3 install aioconsole # from PyPI $ python3 setup.py install # or from the sources $ apython -h usage: apython [-h] [--serve [HOST:] PORT] [--no-readline] [--banner BANNER] [--locals LOCALS] [-m MODULE | FILE] ... Run the given python file or module with a modified asyncio policy replacing the default event loop with an interactive loop. If no argument is given, it simply runs an asynchronous python console. positional arguments: FILE python file to run ARGS extra arguments optional arguments: -h, --help show this help message and exit --serve [HOST:] PORT, -s [HOST:] PORT serve a console on the given interface instead --no-readline force readline disabling --banner BANNER provide a custom banner --locals LOCALS provide custom locals as a dictionary -m MODULE run a python module Simple usage ------------ The following example demonstrates the use of ``await`` inside the console: .. code:: console $ apython Python 3.5.0 (default, Sep 7 2015, 14:12:03) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. --- This console is running in an asyncio event loop. It allows you to wait for coroutines using the 'await' syntax. Try: await asyncio.sleep(1, result=3, loop=loop) --- .. code:: python3 >>> await asyncio.sleep(1, result=3) # Wait one second... 3 >>> Documentation ------------- Find more examples in the documentation_ and the `example directory`_. Limitations ----------- The python console exposed by `aioconsole`_ is quite limited compared to modern consoles such as `IPython`_ or `ptpython`_. Luckily, those projects gained greater asyncio support over the years. In particular, the following use cases overlap with `aioconsole`_ capabilities: - `Embedding a ptpython console in an asyncio program `_ - `Using the await syntax in an IPython console `_ Contact ------- Vincent Michel: vxgmichel@gmail.com .. _aioconsole: https://pypi.python.org/pypi/aioconsole .. _GitHub: https://github.com/vxgmichel/aioconsole .. _input: https://docs.python.org/3/library/functions.html#input .. _print: https://docs.python.org/3/library/functions.html#print .. _exec: https://docs.python.org/3/library/functions.html#exec .. _code.interact: https://docs.python.org/3/library/code.html#code.interact .. _argparse: https://docs.python.org/dev/library/argparse.html .. _stream: https://docs.python.org/3/library/asyncio-stream.html .. _example directory: https://github.com/vxgmichel/aioconsole/blob/main/example .. _documentation: http://aioconsole.readthedocs.io/ .. _PyPI: aioconsole_ .. _IPython: https://ipython.readthedocs.io .. _ptpython: https://github.com/prompt-toolkit/ptpython .. |docs-badge| image:: https://readthedocs.org/projects/aioconsole/badge/?version=latest :target: http://aioconsole.readthedocs.io/ :alt: .. |ci-badge| image:: https://github.com/vxgmichel/aioconsole/workflows/CI/badge.svg :target: https://github.com/vxgmichel/aioconsole/actions?query=branch%3Amain :alt: .. |cov-badge| image:: https://codecov.io/gh/vxgmichel/aioconsole/branch/main/graph/badge.svg :target: https://codecov.io/gh/vxgmichel/aioconsole :alt: .. |version-badge| image:: https://img.shields.io/pypi/v/aioconsole.svg :target: https://pypi.python.org/pypi/aioconsole :alt: .. |pyversion-badge| image:: https://img.shields.io/pypi/pyversions/aioconsole.svg :target: https://pypi.python.org/pypi/aioconsole :alt: vxgmichel-aioconsole-3df7872/aioconsole/000077500000000000000000000000001471042674700203465ustar00rootroot00000000000000vxgmichel-aioconsole-3df7872/aioconsole/__init__.py000066400000000000000000000015531471042674700224630ustar00rootroot00000000000000"""Provide asynchronous equivalent to input, exec and interact. It also includes an interactive event loop, and a command line interface. """ from .execute import aexec, aeval from .console import AsynchronousConsole, interact from .stream import ainput, aprint, get_standard_streams from .events import InteractiveEventLoop, InteractiveEventLoopPolicy from .events import set_interactive_policy, run_console from .command import AsynchronousCli from .server import start_interactive_server from .apython import run_apython __version__ = "0.8.1" __all__ = [ "aexec", "aeval", "ainput", "aprint", "AsynchronousConsole", "interact", "InteractiveEventLoop", "InteractiveEventLoopPolicy", "set_interactive_policy", "run_console", "AsynchronousCli", "start_interactive_server", "get_standard_streams", "run_apython", ] vxgmichel-aioconsole-3df7872/aioconsole/__main__.py000066400000000000000000000000601471042674700224340ustar00rootroot00000000000000from .apython import run_apython run_apython() vxgmichel-aioconsole-3df7872/aioconsole/apython.py000066400000000000000000000125571471042674700224140ustar00rootroot00000000000000"""Provide the apython script.""" import os import sys import ast import runpy import warnings import argparse import traceback from . import events from . import server from . import rlwrap from . import compat ZERO_WIDTH_SPACE = "\u200b" DESCRIPTION = """\ Run the given python file or module with a modified asyncio policy replacing the default event loop with an interactive loop. If no argument is given, it simply runs an asynchronous python console.""" USAGE = """\ usage: apython [-h] [--serve [HOST:] PORT] [--no-readline] [--banner BANNER] [--locals LOCALS] [-m MODULE | FILE] ... """.split( "usage: " )[ 1 ] def exec_pythonstartup(locals_dict): filename = os.environ.get("PYTHONSTARTUP") if filename: if os.path.isfile(filename): with open(filename) as fobj: startupcode = fobj.read() try: locals_dict["__file__"] = filename exec(startupcode, globals(), locals_dict) except Exception: # pragma: no cover traceback.print_exc() finally: locals_dict.pop("__file__", None) else: print(f"Could not open PYTHONSTARTUP - No such file: {filename}") def parse_args(args=None): parser = argparse.ArgumentParser( prog="apython", description=DESCRIPTION, usage=USAGE ) # Options parser.add_argument( "--serve", "-s", metavar="[HOST:] PORT", help="serve a console on the given interface instead", ) parser.add_argument( "--no-readline", dest="readline", action="store_false", help="disable readline support", ) parser.add_argument("--banner", help="provide a custom banner") parser.add_argument( "--locals", type=ast.literal_eval, help="provide custom locals as a dictionary" ) # Hidden option parser.add_argument("--prompt-control", metavar="PC", help=argparse.SUPPRESS) # Input parser.add_argument("-m", dest="module", help="run a python module") parser.add_argument( "filename", metavar="FILE", nargs="?", help="python file to run" ) # Extra arguments parser.add_argument( "args", metavar="ARGS", nargs=argparse.REMAINDER, help="extra arguments" ) namespace = parser.parse_args(args) # If module is provided, filename is actually the fist arg if namespace.module is not None and namespace.filename is not None: namespace.args.insert(0, namespace.filename) # Parse the serve argument if namespace.serve is not None: namespace.serve = server.parse_server(namespace.serve, parser) return namespace def load_readline(): try: import readline # noqa: F401 import rlcompleter # noqa: F401 except ImportError: return False return True def run_apython(args=None): namespace = parse_args(args) if ( namespace.readline and not namespace.serve and compat.platform != "win32" and load_readline() ): # Run python interactive hook in order to configure binding and history support interactive_hook = getattr(sys, "__interactivehook__", None) if interactive_hook: try: interactive_hook() except Exception as exc: warnings.warn(f"Interactive hook failed: {exc!r}", stacklevel=2) code = run_apython_in_subprocess(args, namespace.prompt_control) sys.exit(code) try: sys._argv = sys.argv sys._path = sys.path if namespace.module: sys.argv = [None] + namespace.args sys.path.insert(0, "") events.set_interactive_policy( locals=namespace.locals, banner=namespace.banner, serve=namespace.serve, prompt_control=namespace.prompt_control, ) runpy.run_module(namespace.module, run_name="__main__", alter_sys=True) elif namespace.filename: sys.argv = [None] + namespace.args path = os.path.dirname(os.path.abspath(namespace.filename)) sys.path.insert(0, path) events.set_interactive_policy( locals=namespace.locals, banner=namespace.banner, serve=namespace.serve, prompt_control=namespace.prompt_control, ) runpy.run_path(namespace.filename, run_name="__main__") else: if namespace.locals is None: namespace.locals = {} exec_pythonstartup(namespace.locals) events.run_console( locals=namespace.locals, banner=namespace.banner, serve=namespace.serve, prompt_control=namespace.prompt_control, ) finally: sys.argv = sys._argv sys.path = sys._path sys.exit() def run_apython_in_subprocess(args=None, prompt_control=None): # Default arguments if args is None: args = sys.argv[1:] if prompt_control is None: prompt_control = ZERO_WIDTH_SPACE # Create subprocess proc_args = [ sys.executable, "-m", "aioconsole", "--no-readline", "--prompt-control", prompt_control, ] return rlwrap.rlwrap_process(proc_args + args, prompt_control, use_stderr=True) vxgmichel-aioconsole-3df7872/aioconsole/command.py000066400000000000000000000063251471042674700223440ustar00rootroot00000000000000"""Provide an asynchronous equivalent to the python console.""" import sys import argparse import shlex from . import console class AsynchronousCli(console.AsynchronousConsole): def __init__( self, commands, streams=None, *, prog=None, prompt_control=None, loop=None ): super().__init__(streams=streams, prompt_control=prompt_control, loop=loop) self.prog = prog self.commands = dict(commands) self.commands["help"] = ( self.help_command, argparse.ArgumentParser(description="Display the help message."), ) self.commands["list"] = ( self.list_command, argparse.ArgumentParser(description="Display the command list."), ) self.commands["exit"] = ( self.exit_command, argparse.ArgumentParser(description="Exit the interface."), ) for key, (corofunc, parser) in self.commands.items(): parser.prog = key parser.print_help = lambda file=sys.stderr, *, self=parser: type( parser ).print_help(self, file) def get_default_banner(self): prog = self.prog or sys.argv[0].split("/")[-1] msg = f"Welcome to the CLI interface of {prog}!\n" msg += "Try:\n" msg += " * 'help' to display the help message\n" msg += " * 'list' to display the command list." return msg async def help_command(self, reader, writer): return """\ Type 'help' to display this message. Type 'list' to display the command list. Type ' -h' to display the help message of .""" async def list_command(self, reader, writer): msg = "List of commands:" for key, (corofunc, parser) in sorted(self.commands.items()): usage = parser.format_usage().replace("usage: ", "")[:-1] msg += "\n * " + usage return msg async def exit_command(self, reader, writer): raise SystemExit async def runsource(self, source, filename=None): # Parse the source if source.strip().endswith("\\"): return True source = source.replace("\\\n", "") try: name, *args = shlex.split(source) except ValueError: return False # Get the command if name not in self.commands: self.write(f"Command '{name}' does not exist.\n") await self.flush() return False corofunc, parser = self.commands[name] # Patch print_message so the parser prints to our console parser._print_message = lambda message, file=None: message and self.write( message ) # Parse arguments try: namespace = parser.parse_args(args) except SystemExit: return False # Run the coroutine coro = corofunc(self.reader, self.writer, **vars(namespace)) try: result = await coro except SystemExit: raise # Prompt the traceback or result except BaseException: self.showtraceback() else: if result is not None: self.write(str(result) + "\n") await self.flush() return False vxgmichel-aioconsole-3df7872/aioconsole/compat.py000066400000000000000000000001441471042674700222020ustar00rootroot00000000000000"""Compatibility helpers for the different Python versions.""" import sys platform = sys.platform vxgmichel-aioconsole-3df7872/aioconsole/console.py000066400000000000000000000204651471042674700223710ustar00rootroot00000000000000"""Provide an asynchronous equivalent to the python console.""" import sys import code import pydoc import codeop import signal import asyncio import inspect import functools import traceback from . import stream from . import execute EXTRA_MESSAGE = """\ --- This console is running in an asyncio event loop. It allows you to wait for coroutines using the 'await' syntax. Try: await asyncio.sleep(1, result=3) ---""" # cx_Freeze does not include the help function try: help_function = help except NameError: help_function = None class AsynchronousCompiler(codeop.CommandCompiler): def __init__(self): self.compiler = functools.partial( execute.compile_for_aexec, dont_imply_dedent=True ) class AsynchronousConsole(code.InteractiveConsole): def __init__( self, streams=None, locals=None, filename="", prompt_control=None, *, loop=None, ): super().__init__(locals, filename) # Process arguments if loop is None: loop = asyncio.get_event_loop() if streams is None: streams = stream.get_standard_streams(use_stderr=True, loop=loop) # Attributes self.streams = streams self.loop = loop self.reader = None self.writer = None self.prompt_control = prompt_control self.compile = AsynchronousCompiler() # Populate locals self.locals["asyncio"] = asyncio self.locals["loop"] = self.loop self.locals["print"] = self.print self.locals["help"] = self.help self.locals["ainput"] = self.ainput # Internals self._sigint_received = False @functools.wraps(print) def print(self, *args, **kwargs): kwargs.setdefault("file", self) print(*args, **kwargs) @functools.wraps(help_function) def help(self, obj): self.print(pydoc.render_doc(obj)) @functools.wraps(stream.ainput) async def ainput(self, prompt="", *, streams=None, use_stderr=False, loop=None): # Get the console streams by default if streams is None and use_stderr is False: streams = self.reader, self.writer # Wrap the prompt with prompt control characters if self.prompt_control and self.prompt_control not in prompt: prompt = self.prompt_control + prompt + self.prompt_control # Run ainput return await stream.ainput( prompt, streams=streams, use_stderr=use_stderr, loop=loop ) def get_default_banner(self): cprt = ( 'Type "help", "copyright", "credits" ' 'or "license" for more information.' ) return f"Python {sys.version} on {sys.platform}\n{cprt}\n{EXTRA_MESSAGE}" async def runsource(self, source, filename="", symbol="single"): try: code = self.compile(source, filename, symbol) except (OverflowError, SyntaxError, ValueError): self.showsyntaxerror(filename) return False if code is None: return True await self.runcode(code) return False async def runcode(self, code): try: await execute.aexec( code, local=self.locals, stream=self, filename=self.filename ) except SystemExit: raise except BaseException: self.showtraceback() await self.flush() def resetbuffer(self): self.buffer = [] def handle_sigint(self, task): self._sigint_received = True task.cancel() if task._fut_waiter._loop is not self.loop: task._wakeup(task._fut_waiter) def add_sigint_handler(self): task = asyncio.current_task(loop=self.loop) try: self.loop.add_signal_handler(signal.SIGINT, self.handle_sigint, task) except NotImplementedError: def callback(*args): self.loop.call_soon_threadsafe(self.handle_sigint, task) signal.signal(signal.SIGINT, callback) def remove_sigint_handler(self): try: self.loop.remove_signal_handler(signal.SIGINT) except NotImplementedError: signal.signal(signal.SIGINT, signal.default_int_handler) async def interact(self, banner=None, stop=True, handle_sigint=True): # Get the streams try: if inspect.isawaitable(self.streams): self.reader, self.writer = await self.streams elif self.streams is not None: self.reader, self.writer = self.streams finally: self.streams = None # Interact try: if handle_sigint: self.add_sigint_handler() await self._interact(banner) if stop: raise SystemExit # Exit except SystemExit: if stop: raise # Clean-up finally: if handle_sigint: self.remove_sigint_handler() async def _interact(self, banner=None): # Get ps1 and ps2 try: sys.ps1 except AttributeError: sys.ps1 = ">>> " try: sys.ps2 except AttributeError: sys.ps2 = "... " # Print banner if banner is None: banner = self.get_default_banner() self.write(f"{banner}\n") # Run loop more = 0 while 1: try: if more: prompt = sys.ps2 else: prompt = sys.ps1 try: line = await self.raw_input(prompt) except EOFError: try: self.write("\n") await self.flush() except OSError: pass break else: more = await self.push(line) except asyncio.CancelledError: # Not our cancellation if not self._sigint_received: raise # Manage cancellation self._sigint_received = False self.write("\nKeyboardInterrupt\n") await self.flush() self.resetbuffer() more = 0 async def push(self, line): self.buffer.append(line) source = "\n".join(self.buffer) more = await self.runsource(source, self.filename) if not more: self.resetbuffer() return more async def raw_input(self, prompt=""): return await self.ainput(prompt) def write(self, data): return self.writer.write(data.encode()) async def flush(self): try: await self.writer.drain() except ConnectionResetError: pass # Re-implement showtraceback and showsyntaxerror # to ignore sys.excepthook (set by ubuntu apport for instance) def showtraceback(self): sys.last_type, sys.last_value, last_tb = ei = sys.exc_info() sys.last_traceback = last_tb try: lines = traceback.format_exception(ei[0], ei[1], last_tb.tb_next) self.write("".join(lines)) finally: last_tb = ei = None def showsyntaxerror(self, filename=None): type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb if filename and type is SyntaxError: # Work hard to stuff the correct filename in the exception try: msg, (dummy_filename, lineno, offset, line) = value.args except ValueError: # Not the format we expect; leave it alone pass else: # Stuff in the right filename value = SyntaxError(msg, (filename, lineno, offset, line)) sys.last_value = value lines = traceback.format_exception_only(type, value) self.write("".join(lines)) async def interact( banner=None, streams=None, locals=None, prompt_control=None, stop=True, handle_sigint=True, *, loop=None, ): console = AsynchronousConsole( streams, locals=locals, prompt_control=prompt_control, loop=loop ) await console.interact(banner, stop, handle_sigint) vxgmichel-aioconsole-3df7872/aioconsole/events.py000066400000000000000000000054151471042674700222310ustar00rootroot00000000000000"""Provide an interactive event loop class.""" import asyncio import functools from . import server from . import console class InteractiveEventLoop(asyncio.SelectorEventLoop): """Event loop running a python console.""" console_class = console.AsynchronousConsole def __init__( self, *, selector=None, locals=None, banner=None, serve=None, prompt_control=None, ): self.console = None self.console_task = None self.console_server = None super().__init__(selector=selector) # Factory self.factory = lambda streams: self.console_class( streams, locals=locals, prompt_control=prompt_control, loop=self ) # Local console if serve is None: self.console = self.factory(None) coro = self.console.interact(banner, stop=True, handle_sigint=True) self.console_task = asyncio.ensure_future(coro, loop=self) # Serving console else: host, port = serve coro = server.start_interactive_server( self.factory, host=host, port=port, banner=banner, loop=self ) self.console_server = self.run_until_complete(coro) server.print_server(self.console_server) def close(self): if self.console_task and not self.is_running(): asyncio.Future.cancel(self.console_task) super().close() def __del__(self): if self.console_task and self.console_task.done(): self.console_task.exception() try: super().__del__() except AttributeError: pass class InteractiveEventLoopPolicy(asyncio.DefaultEventLoopPolicy): """Policy to use the interactive event loop by default.""" def __init__(self, *, locals=None, banner=None, serve=None, prompt_control=None): self._loop_factory = functools.partial( InteractiveEventLoop, locals=locals, banner=banner, serve=serve, prompt_control=prompt_control, ) super().__init__() def set_interactive_policy( *, locals=None, banner=None, serve=None, prompt_control=None ): """Use an interactive event loop by default.""" policy = InteractiveEventLoopPolicy( locals=locals, banner=banner, serve=serve, prompt_control=prompt_control ) asyncio.set_event_loop_policy(policy) def run_console(*, locals=None, banner=None, serve=None, prompt_control=None): """Run the interactive event loop.""" loop = InteractiveEventLoop( locals=locals, banner=banner, serve=serve, prompt_control=prompt_control ) asyncio.set_event_loop(loop) try: loop.run_forever() except KeyboardInterrupt: pass vxgmichel-aioconsole-3df7872/aioconsole/execute.py000066400000000000000000000126021471042674700223630ustar00rootroot00000000000000"""Provide an asynchronous equivalent *to exec*.""" import ast import codeop from io import StringIO from tokenize import generate_tokens, STRING, TokenError CORO_NAME = "__corofn" CORO_DEF = f"async def {CORO_NAME}(): " CORO_CODE = CORO_DEF + "return (None, locals())\n" def make_arg(key, annotation=None): """Make an ast function argument.""" arg = ast.arg(key, annotation) arg.lineno, arg.col_offset = 0, 0 return arg def full_update(dct, values): """Fully update a dictionary.""" dct.clear() dct.update(values) def exec_single_result(obj, local, stream): """Reproduce the exec behavior in single mode (print and builtins._)""" local["_"] = obj if obj is not None: print(repr(obj), file=stream) class ReturnChecker(ast.NodeVisitor): def __init__(self, filename): super().__init__() self.filename = filename def visit_FunctionDef(self, node: ast.FunctionDef): return # skip functions def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef): return # async functions too def visit_Return(self, node: ast.Return): raise SyntaxError( "'return' outside function", (self.filename, node.lineno, node.col_offset + 1, None), ) def visit_Yield(self, node: ast.Yield): raise SyntaxError( "'yield' outside function", (self.filename, node.lineno, node.col_offset + 1, None), ) def visit_YieldFrom(self, node: ast.YieldFrom): self.visit_Yield(node) # handle in the same way as regular yield def make_tree(statement, filename, mode): """Helper for *aexec*.""" # Check for returns and yields ReturnChecker(filename).visit(statement) # Create tree tree = ast.parse(CORO_CODE, filename, "single") # Check expression statement if isinstance(statement, ast.Expr): tree.body[0].body[0].value.elts[0] = statement.value else: tree.body[0].body.insert(0, statement) # Check the coroutine function exec(compile(tree, filename, "single")) if mode == "exec": return ast.Module([tree]) if mode == "single": return ast.Interactive([tree]) assert mode == "eval" raise ValueError("Mode 'eval' is not supported") def make_coroutine_from_tree(wrapped, filename, local): """Make a coroutine from a tree structure.""" dct = {} tree = wrapped.body[0] tree.body[0].args.args = list(map(make_arg, local)) exec(compile(tree, filename, "single"), dct) return dct[CORO_NAME](**local) def get_non_indented_lines(source): try: for token in generate_tokens(StringIO(source).readline): if token.type == STRING: # .start and .end line numbers are one-indexed yield from range(token.start[0], token.end[0]) except TokenError: pass def compile_for_aexec( source, filename, mode, dont_imply_dedent=False, local={}, **kwargs ): """Return a list of (coroutine object, abstract base tree).""" flags = ast.PyCF_ONLY_AST if dont_imply_dedent: flags |= codeop.PyCF_DONT_IMPLY_DEDENT # This flag is not available for python before 3.10 try: flags |= codeop.PyCF_ALLOW_INCOMPLETE_INPUT except AttributeError: pass # Avoid a syntax error by wrapping code with `async def` # Disabling indentation inside multiline strings non_indented = set( # sets are faster for `in` operation get_non_indented_lines(source) ) indented = "\n".join( (" " * 4 if i not in non_indented and line else "") + line for i, line in enumerate(source.split("\n")) ) coroutine = CORO_DEF + "\n" + indented + "\n" # Compilation is always performed in single mode compiled = compile(coroutine, filename, "single", flags) statements = compiled.body[0].body # Use original source to detect missing newlines, depending on the mode try: compile(source, filename, mode, flags) except SyntaxError: raise return [make_tree(statement, filename, mode) for statement in statements] async def aexec(source, local=None, stream=None, filename=""): """Asynchronous equivalent to *exec*.""" if local is None: local = {} if isinstance(source, str): source = compile_for_aexec(source, filename, "exec") for tree in source: coro = make_coroutine_from_tree(tree, filename, local=local) result, new_local = await coro if isinstance(tree, ast.Interactive): exec_single_result(result, new_local, stream) full_update(local, new_local) async def aeval(source, local=None): """Asynchronous equivalent to *eval*.""" if local is None: local = {} if not isinstance(local, dict): raise TypeError("globals must be a dict") # Ensure that the result key is unique within the local namespace key = "__aeval_result__" while key in local: key += "_" # Perform syntax check to ensure the input is a valid eval expression try: ast.parse(source, mode="eval") except SyntaxError: raise # Assign the result of the expression to a known variable wrapped_code = f"{key} = {source}" # Use aexec to evaluate the wrapped code within the given local namespace await aexec(wrapped_code, local=local) # Return the result from the local namespace return local.pop(key) vxgmichel-aioconsole-3df7872/aioconsole/rlwrap.py000066400000000000000000000073451471042674700222400ustar00rootroot00000000000000"""Provide a readline wrapper to control a subprocess.""" import sys import ctypes import signal import builtins import subprocess from concurrent.futures import ThreadPoolExecutor from . import compat if compat.platform == "darwin": import fcntl def rlwrap_process(args, prompt_control, use_stderr=False): assert len(prompt_control) == 1 # Start process process = subprocess.Popen( args, bufsize=0, universal_newlines=True, stdin=subprocess.PIPE, **{"stderr" if use_stderr else "stdout": subprocess.PIPE}, ) # Readline wrapping return _rlwrap(process, prompt_control, use_stderr) def _rlwrap(process, prompt_control, use_stderr=False): # Get source and destination source = process.stderr if use_stderr else process.stdout dest = sys.stderr if use_stderr else sys.stdout # Check prompt control assert len(prompt_control) == 1 # Run background task with ThreadPoolExecutor(1) as executor: future = executor.submit(wait_for_prompt, source, dest, prompt_control) # Loop over prompts while process.poll() is None: # Get prompt try: prompt = future.result() except KeyboardInterrupt: process.send_signal(signal.SIGINT) continue except EOFError: break else: future = executor.submit(wait_for_prompt, source, dest, prompt_control) # Get user input try: raw = input(prompt, use_stderr=use_stderr) + "\n" except KeyboardInterrupt: process.send_signal(signal.SIGINT) continue except EOFError: break else: process.stdin.write(raw) # Close and wait process streams process.stdin.close() future.exception() # Wait process and return code return process.wait() def wait_for_prompt(src, dest, prompt_control, buffersize=1): def read(): value = src.read(buffersize) if value: return value raise EOFError def write(arg): if arg: dest.write(arg) dest.flush() # Prevent exception in macOS with large output (issue #42) if compat.platform == "darwin": fcntl.fcntl(dest.fileno(), fcntl.F_SETFL, 0) # Wait for first prompt control while True: current = read() if prompt_control in current: break write(current) preprompt, current = current.split(prompt_control, 1) write(preprompt) # Wait for second prompt control while prompt_control not in current: current += read() prompt, postprompt = current.split(prompt_control, 1) write(postprompt) return prompt def input(prompt="", use_stderr=False): # Use readline if possible try: import readline # noqa except ImportError: return builtins.input(prompt) # Use stdout if not use_stderr: return builtins.input(prompt) api = ctypes.pythonapi # Cross-platform compatibility if compat.platform == "darwin": stdin = "__stdinp" stderr = "__stderrp" else: stdin = "stdin" stderr = "stderr" # Get standard streams try: fin = ctypes.c_void_p.in_dll(api, stdin) ferr = ctypes.c_void_p.in_dll(api, stderr) # Cygwin fallback except ValueError: return builtins.input(prompt) # Call readline call_readline = api.PyOS_Readline call_readline.restype = ctypes.c_char_p result = call_readline(fin, ferr, prompt.encode()) # Decode result if len(result) == 0: raise EOFError return result.decode().rstrip("\n") vxgmichel-aioconsole-3df7872/aioconsole/server.py000066400000000000000000000055111471042674700222300ustar00rootroot00000000000000"""Serve the python console using socket communication.""" import asyncio import socket from functools import partial from . import compat from . import console async def handle_connect(reader, writer, factory, banner=None): streams = reader, writer interface = factory(streams=streams) await interface.interact(banner=banner, stop=False, handle_sigint=False) writer.close() async def start_interactive_server( factory=console.AsynchronousConsole, host=None, port=None, path=None, banner=None, *, loop=None, ): if compat.platform == "win32" and port is None: raise ValueError("A TCP port should be provided") if (port is None) == (path is None): raise ValueError("Either a TCP port or a UDS path should be provided") if port is not None: # Override asyncio behavior (i.e serve on all interfaces by default) host = host or "localhost" start_server = partial(asyncio.start_server, host=host, port=port) else: start_server = partial(asyncio.start_unix_server, path=path) client_connected = partial(handle_connect, factory=factory, banner=banner) server = await start_server(client_connected) return server async def start_console_server( host=None, port=None, path=None, locals=None, filename="", banner=None, prompt_control=None, *, loop=None, ): def factory(streams): client_locals = dict(locals) if locals is not None else None return console.AsynchronousConsole( streams=streams, locals=client_locals, filename=filename, prompt_control=prompt_control, ) server = await start_interactive_server( factory, host=host, port=port, path=path, banner=banner, loop=loop ) return server def print_server(server, name="console", file=None): interface = server.sockets[0].getsockname() AF_UNIX = None if compat.platform == "win32" else socket.AF_UNIX if server.sockets[0].family != AF_UNIX: interface = "{}:{}".format(*interface) print(f"The {name} is being served on {interface}", file=file) def run(host=None, port=None, path=None): loop = asyncio.get_event_loop() coro = start_interactive_server(host=host, port=port, path=path) loop.server = loop.run_until_complete(coro) print_server(loop.server) try: loop.run_forever() except KeyboardInterrupt: pass def parse_server(server, parser=None): try: host, port = server.rsplit(":", maxsplit=1) except ValueError: host, port = "localhost", server try: port = int(port) except (ValueError, TypeError): msg = f"{server!r} is not a valid server [HOST:]PORT" if not parser: raise ValueError(msg) parser.error(msg) return host, port vxgmichel-aioconsole-3df7872/aioconsole/stream.py000066400000000000000000000230671471042674700222230ustar00rootroot00000000000000"""Provide an asynchronous equivalent to *input*.""" import os import sys import stat import weakref import asyncio import selectors from collections import deque from threading import Thread from concurrent.futures import Future from . import compat class ProtectedPipe: """Wrapper to protect a pipe from being closed.""" def __init__(self, pipe): self.pipe = pipe def fileno(self): return self.pipe.fileno() def close(self): pass def is_pipe_transport_compatible(pipe): if compat.platform == "win32": return False try: fileno = pipe.fileno() except (OSError, AttributeError): return False mode = os.fstat(fileno).st_mode is_char = stat.S_ISCHR(mode) is_fifo = stat.S_ISFIFO(mode) is_socket = stat.S_ISSOCK(mode) if not (is_char or is_fifo or is_socket): return False # Fail early when the file descriptor cannot be registered. # This happens with docker containers for instance. # See issue #102: https://github.com/vxgmichel/aioconsole/issues/102 try: with selectors.DefaultSelector() as selector: selector.register(fileno, selectors.EVENT_READ | selectors.EVENT_WRITE) except OSError: return False return True async def run_as_daemon(func, *args): future = Future() future.set_running_or_notify_cancel() # A bug in python 3.7 makes it a bad idea to set a BaseException # in a wrapped future (see except statement in asyncio.Task.__wakeup) # Instead, we'll wrap base exceptions into exceptions and unwrap them # on the other side of the call. class BaseExceptionWrapper(Exception): pass def daemon(): try: result = func(*args) except Exception as e: future.set_exception(e) except BaseException as e: future.set_exception(BaseExceptionWrapper(e)) else: future.set_result(result) Thread(target=daemon, daemon=True).start() try: return await asyncio.wrap_future(future) except BaseExceptionWrapper as exc: raise exc.args[0] class StandardStreamReaderProtocol(asyncio.StreamReaderProtocol): def connection_made(self, transport): # The connection is already made if self._stream_reader._transport is not None: return # Make the connection super().connection_made(transport) def connection_lost(self, exc): # Copy the inner state state = self.__dict__.copy() # Call the parent super().connection_lost(exc) # Restore the inner state self.__dict__.update(state) class StandardStreamReader(asyncio.StreamReader): async def readuntil(self, separator=b"\n"): # Re-implement `readuntil` to work around self._limit. # The limit is still useful to prevent the internal buffer # from growing too large when it's not necessary, but it # needs to be disabled when the user code is purposely # reading from stdin. while True: try: return await super().readuntil(separator) except asyncio.LimitOverrunError as e: if self._buffer.startswith(separator, e.consumed): chunk = self._buffer[: e.consumed + len(separator)] del self._buffer[: e.consumed + len(separator)] self._maybe_resume_transport() return bytes(chunk) await self._wait_for_data("readuntil") class StandardStreamWriter(asyncio.StreamWriter): def __del__(self): # No `__del__` method for StreamWriter in Python 3.10 and before try: parent_del = super().__del__ except AttributeError: return # Do not attempt to close the transport if the loop is closed try: asyncio.get_running_loop() except RuntimeError: return parent_del() def write(self, data): if isinstance(data, str): data = data.encode() super().write(data) class NonFileStreamReader: def __init__(self, stream, *, loop=None): if loop is None: loop = asyncio.get_event_loop() self.loop = loop self.stream = stream self.eof = False def at_eof(self): return self.eof async def readline(self): try: data = await run_as_daemon(self.stream.readline) except AttributeError: raise RuntimeError("ainput(): lost sys.stdin") if isinstance(data, str): data = data.encode() self.eof = not data return data async def read(self, n=-1): try: data = await run_as_daemon(self.stream.read, n) except AttributeError: raise RuntimeError("ainput(): lost sys.stdin") if isinstance(data, str): data = data.encode() self.eof = not data return data def __aiter__(self): return self async def __anext__(self): val = await self.readline() if val == b"": raise StopAsyncIteration return val class NonFileStreamWriter: def __init__(self, stream, *, loop=None): if loop is None: loop = asyncio.get_event_loop() self.loop = loop self.stream = stream self.buffer = deque() self.write_task = None self.task_finalizer = None def write(self, data): if self.stream is None: raise RuntimeError("This writer stream is already closed") if isinstance(data, bytes): data = data.decode() self.buffer.append(data) if self.write_task is not None and not self.write_task.done(): return if self.write_task is not None and self.write_task.done(): self.write_task = None self.task_finalizer() self.write_task = asyncio.ensure_future( _nonfile_stream_writer_task_target(self.buffer, self.stream) ) self.task_finalizer = weakref.finalize(self, self.write_task.result) async def drain(self): if self.write_task is not None: try: await self.write_task finally: self.write_task = None self.task_finalizer.detach() def close(self): self.stream = None def is_closing(self): return self.stream is None and self.write_task is not None async def wait_closed(self): await self.drain() async def _nonfile_stream_writer_task_target(data_buffer, stream): loop = asyncio.get_event_loop() while data_buffer: data = data_buffer.popleft() await loop.run_in_executor(None, stream.write, data) if hasattr(stream, "flush"): await loop.run_in_executor(None, stream.flush) async def open_standard_pipe_connection(pipe_in, pipe_out, pipe_err, *, loop=None): if loop is None: loop = asyncio.get_event_loop() # Reader in_reader = StandardStreamReader(loop=loop) protocol = StandardStreamReaderProtocol(in_reader, loop=loop) await loop.connect_read_pipe(lambda: protocol, ProtectedPipe(pipe_in)) # Out writer out_transport, _ = await loop.connect_write_pipe( lambda: protocol, ProtectedPipe(pipe_out) ) out_writer = StandardStreamWriter(out_transport, protocol, in_reader, loop) # Err writer err_transport, _ = await loop.connect_write_pipe( lambda: protocol, ProtectedPipe(pipe_err) ) err_writer = StandardStreamWriter(err_transport, protocol, in_reader, loop) # Set the write buffer limits to zero # This way, `await stream.drain()` can be used to make sure the buffer is flushed out_transport.set_write_buffer_limits(high=0, low=0) err_transport.set_write_buffer_limits(high=0, low=0) # Return return in_reader, out_writer, err_writer async def create_standard_streams(stdin, stdout, stderr, *, loop=None): if all(map(is_pipe_transport_compatible, (stdin, stdout, stderr))): return await open_standard_pipe_connection(stdin, stdout, stderr, loop=loop) return ( NonFileStreamReader(stdin, loop=loop), NonFileStreamWriter(stdout, loop=loop), NonFileStreamWriter(stderr, loop=loop), ) async def get_standard_streams(*, cache={}, use_stderr=False, loop=None): if loop is None: loop = asyncio.get_event_loop() args = sys.stdin, sys.stdout, sys.stderr key = args, loop if cache.get(key) is None: cache[key] = await create_standard_streams(*args, loop=loop) in_reader, out_writer, err_writer = cache[key] return in_reader, err_writer if use_stderr else out_writer async def ainput(prompt="", *, streams=None, use_stderr=False, loop=None): """Asynchronous equivalent to *input*.""" # Get standard streams if streams is None: streams = await get_standard_streams(use_stderr=use_stderr, loop=loop) reader, writer = streams # Write prompt writer.write(prompt.encode()) await writer.drain() # Get data data = await reader.readline() # Decode data data = data.decode() # Return or raise EOF if not data.endswith("\n"): raise EOFError return data.rstrip("\n") async def aprint( *values, sep=None, end="\n", flush=True, streams=None, use_stderr=False, loop=None ): """Asynchronous equivalent to *print*.""" # Get standard streams if streams is None: streams = await get_standard_streams(use_stderr=use_stderr, loop=loop) _, writer = streams print(*values, sep=sep, end=end, flush=False, file=writer) if flush: await writer.drain() vxgmichel-aioconsole-3df7872/docs/000077500000000000000000000000001471042674700171435ustar00rootroot00000000000000vxgmichel-aioconsole-3df7872/docs/conf.py000066400000000000000000000011641471042674700204440ustar00rootroot00000000000000"""Sphinx configuration for aioconsole documentation.""" VERSION = ( open("../aioconsole/__init__.py").read().split('__version__ = "')[1].split('"')[0] ) project = "aioconsole" version = VERSION author = "Vincent Michel" copyright = "2020, Vincent Michel" master_doc = "index" highlight_language = "python" extensions = ["sphinx.ext.autodoc"] html_theme = "sphinx_rtd_theme" html_context = { "display_github": True, "github_user": "vxgmichel", "github_repo": "aioconsole", "github_version": "main", "conf_py_path": "/docs/", "source_suffix": ".rst", } suppress_warnings = ["image.nonlocal_uri"] vxgmichel-aioconsole-3df7872/docs/index.rst000066400000000000000000000247321471042674700210140ustar00rootroot00000000000000aioconsole ========== .. image:: https://readthedocs.org/projects/aioconsole/badge/?version=latest :target: http://aioconsole.readthedocs.io/ :alt: .. image:: https://github.com/vxgmichel/aioconsole/workflows/CI/badge.svg :target: https://github.com/vxgmichel/aioconsole/actions?query=branch%3Amain :alt: .. image:: https://codecov.io/gh/vxgmichel/aioconsole/branch/main/graph/badge.svg :target: https://codecov.io/gh/vxgmichel/aioconsole :alt: .. image:: https://img.shields.io/pypi/v/aioconsole.svg :target: https://pypi.python.org/pypi/aioconsole :alt: .. image:: https://img.shields.io/pypi/pyversions/aioconsole.svg :target: https://pypi.python.org/pypi/aioconsole :alt: Asynchronous console and interfaces for asyncio aioconsole_ provides: * asynchronous equivalents to `input`_, `exec`_ and `code.interact`_ * an interactive loop running the asynchronous python console * a way to customize and run command line interface using `argparse`_ * `stream`_ support to serve interfaces instead of using standard streams * the ``apython`` script to access asyncio code at runtime without modifying the sources Requirements ------------ * Python \>= 3.8 Installation ------------ aioconsole_ is available on PyPI_ and GitHub_. Both of the following commands install the ``aioconsole`` package and the ``apython`` script. .. sourcecode:: console $ pip3 install aioconsole # from PyPI $ python3 setup.py install # or from the sources $ apython -h usage: apython [-h] [--serve [HOST:] PORT] [--no-readline] [--banner BANNER] [--locals LOCALS] [-m MODULE | FILE] ... Asynchronous console -------------------- The `example directory`_ includes a `slightly modified version`_ of the `echo server from the asyncio documentation`_. It runs an echo server on a given port and save the received messages in ``loop.history``. It runs fine and doesn't use any ``aioconsole`` function: .. sourcecode:: console $ python3 -m example.echo 8888 The echo service is being served on 127.0.0.1:8888 In order to access the program while it’s running, simply replace ``python3`` with ``apython`` and redirect ``stdout`` so the console is not polluted by ``print`` statements (``apython`` uses ``stderr``): .. sourcecode:: console $ apython -m example.echo 8888 > echo.log Python 3.5.0 (default, Sep 7 2015, 14:12:03) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. --- This console is running in an asyncio event loop. It allows you to wait for coroutines using the 'await' syntax. Try: await asyncio.sleep(1, result=3, loop=loop) --- >>> This looks like the standard python console, with an extra message. It suggests using the ``await`` syntax (``yield from`` for python 3.4): .. sourcecode:: python3 >>> await asyncio.sleep(1, result=3, loop=loop) # Wait one second... 3 >>> The ``locals`` contain a reference to the event loop: .. sourcecode:: python3 >>> dir() ['__doc__', '__name__', 'asyncio', 'loop'] >>> loop >>> So we can access the ``history`` of received messages: .. sourcecode:: python3 >>> loop.history defaultdict(, {}) >>> sum(loop.history.values(), []) [] Let’s send a message to the server using a netcat_ client: .. sourcecode:: console $ nc localhost 8888 Hello! Hello! The echo server behaves correctly. It is now possible to retrieve the message: .. sourcecode:: python3 >>> sum(loop.history.values(), []) ['Hello!'] The console also supports ``Ctrl-C`` and ``Ctrl-D`` signals: .. sourcecode:: python3 >>> ^C KeyboardInterrupt >>> # Ctrl-D $ All this is implemented by setting ``InteractiveEventLoop`` as default event loop. It simply is a selector loop that schedules ``aioconsole.interact()`` coroutine when it’s created. Serving the console ------------------- Moreover, ``aioconsole.interact()`` supports `stream objects`_ so it can be used along with `asyncio.start\_server`_ to serve the python console. The ``aioconsole.start_interactive_server`` coroutine does exactly that. A backdoor can be introduced by simply adding the following line in the program: .. sourcecode:: python3 server = await aioconsole.start_interactive_server( host='localhost', port=8000) This is actually very similar to the `eventlet.backdoor module`_. It is also possible to use the ``--serve`` option so it is not necessary to modify the code: .. sourcecode:: console $ apython --serve :8889 -m example.echo 8888 The console is being served on 0.0.0.0:8889 The echo service is being served on 127.0.0.1:8888 Then connect using netcat_ and optionally, rlwrap_: .. sourcecode:: console $ rlwrap nc localhost 8889 Python 3.5.0 (default, Sep 7 2015, 14:12:03) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. --- This console is running in an asyncio event loop. It allows you to wait for coroutines using the 'await' syntax. Try: await asyncio.sleep(1, result=3, loop=loop) --- >>> Great! Anyone can now forkbomb your machine: .. sourcecode:: python3 >>> import os >>> os.system(':(){ :|:& };:') Command line interfaces ----------------------- The package also provides an ``AsychronousCli`` object. It is initialized with a dictionary of commands and can be scheduled with the coroutine ``async_cli.interact()``. A dedicated command line interface to the echo server is defined in `example/cli.py`_. In this case, the command dictionary is defined as: .. sourcecode:: python3 commands = {'history': (get_history, parser)} where ``get_history`` is a coroutine and ``parser`` an `ArgumentParser`_ from the `argparse`_ module. The arguments of the parser will be passed as keywords arguments to the coroutine. Let’s run the command line interface: .. sourcecode:: console $ python3 -m example.cli 8888 > cli.log Welcome to the CLI interface of echo! Try: * 'help' to display the help message * 'list' to display the command list. >>> The ``help`` and ``list`` commands are generated automatically: .. sourcecode:: console >>> help Type 'help' to display this message. Type 'list' to display the command list. Type ' -h' to display the help message of . >>> list List of commands: * help [-h] * history [-h] [--pattern PATTERN] * list [-h] >>> The ``history`` command defined earlier can be found in the list. Note that it has an ``help`` option and a ``pattern`` argument: .. sourcecode:: console >>> history -h usage: history [-h] [--pattern PATTERN] Display the message history optional arguments: -h, --help show this help message and exit --pattern PATTERN, -p PATTERN pattern to filter hostnames Example usage of the ``history`` command: .. sourcecode:: console >>> history No message in the history >>> # A few messages later >>> history Host 127.0.0.1: 0. Hello! 1. Bye! Host 192.168.0.3 0. Sup! >>> history -p 127.* Host 127.0.0.1: 0. Hello! 1. Bye! Serving interfaces ------------------ Just like ``asyncio.interact()``, ``AsynchronousCli`` can be initialized with any pair of `streams`_. It can be used along with `asyncio.start\_server`_ to serve the command line interface. The previous `example`_ provides this functionality through the ``--serve-cli`` option: .. sourcecode:: console $ python3 -m example.cli 8888 --serve-cli 8889 The command line interface is being served on 127.0.0.1:8889 The echo service is being served on 127.0.0.1:8888 It’s now possible to access the interface using netcat_: .. sourcecode:: console $ rlwrap nc localhost 8889 Welcome to the CLI interface of echo! Try: * 'help' to display the help message * 'list' to display the command list. >>> It is also possible to combine the example with the ``apython`` script to add an extra access for debugging: .. sourcecode:: console $ apython --serve 8887 -m example.cli 8888 --serve-cli 8889 The console is being served on 127.0.0.1:8887 The command line interface is being served on 127.0.0.1:8889 The echo service is being served on 127.0.0.1:8888 Limitations ----------- The python console exposed by `aioconsole`_ is quite limited compared to modern consoles such as `IPython`_ or `ptpython`_. Luckily, those projects gained greater asyncio support over the years. In particular, the following use cases overlap with `aioconsole`_ capabilities: - `Embedding a ptpython console in an asyncio program `_ - `Using the await syntax in an IPython console `_ Contact ------- Vincent Michel: vxgmichel@gmail.com .. _aioconsole: https://pypi.python.org/pypi/aioconsole .. _GitHub: https://github.com/vxgmichel/aioconsole .. _input: https://docs.python.org/3/library/functions.html#input .. _exec: https://docs.python.org/3/library/functions.html#exec .. _code.interact: https://docs.python.org/2/library/code.html#code.interact .. _argparse: https://docs.python.org/dev/library/argparse.html .. _stream: https://docs.python.org/3.4/library/asyncio-stream.html .. _example directory: https://github.com/vxgmichel/aioconsole/blob/master/example .. _example/echo.py: https://github.com/vxgmichel/aioconsole/blob/master/example/echo.py .. _echo server from the asyncio documentation: https://docs.python.org/3/library/asyncio-stream.html#tcp-echo-server-using-streams .. _asyncio.start\_server: https://docs.python.org/3.4/library/asyncio-stream.html#asyncio.start_server .. _eventlet.backdoor module: http://eventlet.net/doc/modules/backdoor.html#backdoor-python-interactive-interpreter-within-a-running-process .. _example/cli.py: https://github.com/vxgmichel/aioconsole/blob/master/example/cli.py .. _ArgumentParser: https://docs.python.org/dev/library/argparse.html#argparse.ArgumentParser .. _streams: stream_ .. _stream objects: stream_ .. _slightly modified version: `example/echo.py`_ .. _example: `example/cli.py`_ .. _PyPI: aioconsole_ .. _netcat: https://linux.die.net/man/1/nc .. _rlwrap: https://linux.die.net/man/1/rlwrap .. _IPython: https://ipython.readthedocs.io .. _ptpython: https://github.com/prompt-toolkit/ptpython vxgmichel-aioconsole-3df7872/docs/requirements.txt000066400000000000000000000000211471042674700224200ustar00rootroot00000000000000sphinx_rtd_theme vxgmichel-aioconsole-3df7872/example/000077500000000000000000000000001471042674700176465ustar00rootroot00000000000000vxgmichel-aioconsole-3df7872/example/__init__.py000066400000000000000000000000261471042674700217550ustar00rootroot00000000000000"""Example module.""" vxgmichel-aioconsole-3df7872/example/cli.py000066400000000000000000000044201471042674700207670ustar00rootroot00000000000000"""Command line interface for echo server.""" import fnmatch import asyncio import argparse from aioconsole import AsynchronousCli, start_interactive_server from aioconsole.server import parse_server, print_server from . import echo async def get_history(reader, writer, pattern=None): history = asyncio.get_event_loop().history if not history: return "No message in the history" if pattern: history = {host: history[host] for host in fnmatch.filter(history, pattern)} if not history: return "No host match the given pattern" for host in history: writer.write(f"Host {host}:\n".encode()) for i, message in enumerate(history[host]): writer.write(f" {i}. {message}\n".encode()) def make_cli(streams=None): parser = argparse.ArgumentParser(description="Display the message history") parser.add_argument("--pattern", "-p", type=str, help="pattern to filter hostnames") commands = {"history": (get_history, parser)} return AsynchronousCli(commands, streams, prog="echo") def parse_args(args=None): parser = argparse.ArgumentParser( description="Run the echo server and a command line interface." ) parser.add_argument( "server", metavar="[HOST:]PORT", type=str, help="interface for the echo server, default host is localhost", ) parser.add_argument( "--serve-cli", metavar="[HOST:]PORT", type=str, help="serve the command line interface on the given host+port " "instead of using the standard streams", ) namespace = parser.parse_args(args) host, port = parse_server(namespace.server, parser) if namespace.serve_cli is not None: serve_cli = parse_server(namespace.serve_cli, parser) else: serve_cli = None return host, port, serve_cli def main(args=None): host, port, serve_cli = parse_args(args) if serve_cli: cli_host, cli_port = serve_cli coro = start_interactive_server(make_cli, cli_host, cli_port) server = asyncio.get_event_loop().run_until_complete(coro) print_server(server, "command line interface") else: asyncio.ensure_future(make_cli().interact()) return echo.run(host, port) if __name__ == "__main__": main() vxgmichel-aioconsole-3df7872/example/dice.py000066400000000000000000000013161471042674700211250ustar00rootroot00000000000000"""Run a CLI to simulate dice throws.""" import random import asyncio import argparse from aioconsole import AsynchronousCli async def dice(reader, writer, faces): for _ in range(3): await asyncio.sleep(0.33) writer.write(".") await writer.drain() writer.write("\n") return random.randint(1, faces) def main(): parser = argparse.ArgumentParser(description="Throw a dice.") parser.add_argument( "--faces", "-f", metavar="N", type=int, default=6, help="Number of faces" ) cli = AsynchronousCli({"dice": (dice, parser)}, prog="dice") loop = asyncio.get_event_loop() loop.run_until_complete(cli.interact()) if __name__ == "__main__": main() vxgmichel-aioconsole-3df7872/example/echo.py000066400000000000000000000022171471042674700211400ustar00rootroot00000000000000import sys import asyncio import collections async def handle_echo(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): loop = asyncio.get_event_loop() data = await reader.readline() message = data.decode() addr = writer.get_extra_info("peername") loop.history[addr[0]].append(message.strip()) writer.write(data) await writer.drain() writer.close() await writer.wait_closed() async def run(host: str = "localhost", port: int = 8000): loop = asyncio.get_event_loop() loop.history = collections.defaultdict(list) loop.server = await asyncio.start_server(handle_echo, host, port) interface = "{}:{}".format(*loop.server.sockets[0].getsockname()) print(f"The echo service is being served on {interface}") async with loop.server: await loop.server.serve_forever() def main(args: list[str]): (server,) = args[1:] if ":" not in server: coro = run(port=int(server)) else: host, port = server.split(":") coro = run(host, int(port)) try: asyncio.run(coro) except KeyboardInterrupt: pass if __name__ == "__main__": main(sys.argv) vxgmichel-aioconsole-3df7872/pyproject.toml000066400000000000000000000030761471042674700211350ustar00rootroot00000000000000[build-system] requires = ["setuptools >= 69.5"] build-backend = "setuptools.build_meta" [project] name = "aioconsole" dynamic = ["version"] description = "Asynchronous console and interfaces for asyncio" readme = {file = "README.rst", content-type = "text/x-rst"} license = {file = "LICENSE"} requires-python = ">=3.8" authors = [ { name = "Vincent Michel", email = "vxgmichel@gmail.com" }, ] classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3 :: Only", ] [project.optional-dependencies] dev = [ "pytest", "pytest-asyncio", "pytest-cov", "pytest-repeat", 'uvloop; python_implementation != "PyPy" and sys_platform != "win32"', ] [tool.setuptools] packages = ["aioconsole"] [tool.setuptools.dynamic] version = {attr = "aioconsole.__version__"} [project.scripts] apython = "aioconsole:run_apython" [project.urls] Homepage = "https://github.com/vxgmichel/aioconsole" [tool.pytest.ini_options] addopts = "--strict-markers --cov aioconsole --strict-markers --count 2 -vv" testpaths = ["tests"] [tool.black] line-length = 88 target_version = ["py38", "py39", "py310", "py311", "py312", "py313"] [tool.coverage.report] exclude_also = ["if TYPE_CHECKING:", "assert False"] [tool.ruff] ignore = ["E501", "F403"] vxgmichel-aioconsole-3df7872/tests/000077500000000000000000000000001471042674700173555ustar00rootroot00000000000000vxgmichel-aioconsole-3df7872/tests/conftest.py000066400000000000000000000013621471042674700215560ustar00rootroot00000000000000import pytest import asyncio def import_uvloop(): try: import uvloop except ImportError: return None else: return uvloop @pytest.fixture( params=( "default", "uvloop", ), ) def event_loop_policy(request): if request.param == "default": return asyncio.DefaultEventLoopPolicy() elif request.param == "uvloop": uvloop = import_uvloop() if uvloop is None: pytest.skip("uvloop is not installed") return uvloop.EventLoopPolicy() return request.param @pytest.fixture def is_uvloop(event_loop_policy): uvloop = import_uvloop() if uvloop is None: return False return isinstance(event_loop_policy, uvloop.EventLoopPolicy) vxgmichel-aioconsole-3df7872/tests/test_apython.py000066400000000000000000000163471471042674700224630ustar00rootroot00000000000000import io import sys from contextlib import contextmanager from unittest.mock import Mock, patch, call import pytest from aioconsole import InteractiveEventLoop, apython, rlwrap, compat startupfile = """ def hehe(): return 42 foo = 1 # Imports work import math r = math.cos(0) # Exec works and is visible from the interpreter s = 'from pprint import pprint' exec(s) """ @contextmanager def mock_module(name): try: module = sys.modules.get(name) sys.modules[name] = Mock() yield sys.modules[name] finally: if module is None: del sys.modules[name] else: sys.modules[name] = module @pytest.fixture(params=["linux", "darwin", "win32"]) def platform(request): with patch("aioconsole.compat.platform", new=request.param): yield request.param @pytest.fixture def mock_readline(platform): with mock_module("readline"): with patch("aioconsole.rlwrap.ctypes") as m_ctypes: if platform == "darwin": stdin = "__stdinp" stderr = "__stderrp" else: stdin = "stdin" stderr = "stderr" def readline(fin, ferr, prompt): sys.stderr.write(prompt.decode()) return sys.stdin.readline().encode() api = m_ctypes.pythonapi call_readline = api.PyOS_Readline call_readline.side_effect = readline if platform == "darwin": with patch("aioconsole.rlwrap.fcntl", create=True): yield call_readline else: yield call_readline if call_readline.called: m_ctypes.c_void_p.in_dll.assert_has_calls( [call(api, stdin), call(api, stderr)] ) @pytest.fixture(params=["readline", "no-readline"]) def use_readline(request, mock_readline, platform): if request.param == "readline": # Readline tests hang on windows for some reason if sys.platform == "win32": pytest.xfail() return [] return ["--no-readline"] def test_input_with_stderr_prompt(mock_readline): with patch("sys.stdin", new=io.StringIO("test\n")): assert rlwrap.input(use_stderr=True) == "test" def test_basic_apython_usage(capfd, use_readline): with patch("sys.stdin", new=io.StringIO("1+1\n")): with pytest.raises(SystemExit): apython.run_apython(["--banner=test"] + use_readline) out, err = capfd.readouterr() assert out == "" assert err == "test\n>>> 2\n>>> \n" def test_missing_readline(capfd, use_readline): sys.modules["readline"] = None with patch("sys.stdin", new=io.StringIO("1+1\n")): with pytest.raises(SystemExit): apython.run_apython(["--banner=test"] + use_readline) out, err = capfd.readouterr() assert out == "" assert err == "test\n>>> 2\n>>> \n" def test_interactive_hook_error(capfd, use_readline, platform): sys.modules["readline"].parse_and_bind.side_effect = ZeroDivisionError() with patch("sys.stdin", new=io.StringIO("1+1\n")): with pytest.raises(SystemExit): with pytest.warns(UserWarning): apython.run_apython(["--banner=test"] + use_readline) out, err = capfd.readouterr() assert out == "" assert err == "test\n>>> 2\n>>> \n" def test_basic_apython_usage_with_sys_argv(capfd, use_readline): with patch("sys.argv", new=["path.py", "--banner=test"] + use_readline): with patch("sys.stdin", new=io.StringIO("1+1\n")): with pytest.raises(SystemExit): apython.run_apython() out, err = capfd.readouterr() assert out == "" assert err == "test\n>>> 2\n>>> \n" def test_apython_with_prompt_control(capfd): with patch("sys.stdin", new=io.StringIO("1+1\n")): with pytest.raises(SystemExit): apython.run_apython( ["--banner=test", "--prompt-control=▲", "--no-readline"] ) out, err = capfd.readouterr() assert out == "" assert err == "test\n▲>>> ▲2\n▲>>> ▲\n" def test_apython_with_prompt_control_and_ainput(capfd): input_string = "await ainput()\nhello\n" with patch("sys.stdin", new=io.StringIO(input_string)): with pytest.raises(SystemExit): apython.run_apython( ["--no-readline", "--banner=test", "--prompt-control=▲"] ) out, err = capfd.readouterr() assert out == "" assert err == "test\n▲>>> ▲▲▲'hello'\n▲>>> ▲\n" def test_apython_with_ainput(capfd, use_readline): input_string = "await ainput()\nhello\n" with patch("sys.stdin", new=io.StringIO(input_string)): with pytest.raises(SystemExit): apython.run_apython(["--banner=test"] + use_readline) out, err = capfd.readouterr() assert out == "" assert err == "test\n>>> 'hello'\n>>> \n" def test_apython_with_stdout_logs(capfd, use_readline): with patch( "sys.stdin", new=io.StringIO('import sys; sys.stdout.write("logging") or 7\n') ): with pytest.raises(SystemExit): apython.run_apython(["--banner=test"] + use_readline) out, err = capfd.readouterr() assert out == "logging" assert err == "test\n>>> 7\n>>> \n" def test_apython_server(capfd): def run_forever(self, orig=InteractiveEventLoop.run_forever): if self.console_server is not None: self.call_later(0, self.stop) return orig(self) with patch("aioconsole.InteractiveEventLoop.run_forever", run_forever): with pytest.raises(SystemExit): apython.run_apython(["--serve=:0"]) out, err = capfd.readouterr() assert out.startswith("The console is being served on") assert err == "" @pytest.mark.skipif( compat.platform == "win32", reason="apython does not run in a subprocess on windows" ) def test_apython_non_existing_file(capfd): with pytest.raises(SystemExit): apython.run_apython(["idontexist.py"]) out, err = capfd.readouterr() assert out == "" assert "No such file or directory" in err assert "idontexist.py" in err @pytest.mark.skipif( compat.platform == "win32", reason="apython does not run in a subprocess on windows" ) def test_apython_non_existing_module(capfd): with pytest.raises(SystemExit): apython.run_apython(["-m", "idontexist"]) out, err = capfd.readouterr() assert out == "" assert "No module named idontexist" in err def test_apython_pythonstartup(capfd, use_readline, monkeypatch, tmpdir): python_startup = tmpdir / "python_startup.py" monkeypatch.setenv("PYTHONSTARTUP", str(python_startup)) python_startup.write(startupfile) test_vectors = ( ("print(foo)\n", "", ">>> 1\n"), ("print(hehe())\n", "", ">>> 42\n"), ("print(r)\n", "", ">>> 1.0\n"), ("pprint({1:2})\n", "{1: 2}\n", ">>> >>> \n"), ) inputstr = "".join([tv[0] for tv in test_vectors]) outstr = "".join([tv[1] for tv in test_vectors]) errstr = "test\n" + "".join([tv[2] for tv in test_vectors]) with patch("sys.stdin", new=io.StringIO(inputstr)): with pytest.raises(SystemExit): apython.run_apython(["--banner=test"] + use_readline) out, err = capfd.readouterr() assert out == outstr assert err == errstr vxgmichel-aioconsole-3df7872/tests/test_command.py000066400000000000000000000047031471042674700224100ustar00rootroot00000000000000import io import sys import argparse import pytest from aioconsole import AsynchronousCli testdata = { "simple_command": ( "hello\n", """\ Welcome to the CLI interface of hello! Try: * 'help' to display the help message * 'list' to display the command list. [Hello!] Hello! [Hello!] \n""", ), "simple_command_with_arg": ( "hello -n Neil\n", """\ Welcome to the CLI interface of hello! Try: * 'help' to display the help message * 'list' to display the command list. [Hello!] Hello Neil! [Hello!] \n""", ), "list_command": ( "list\n", """\ Welcome to the CLI interface of hello! Try: * 'help' to display the help message * 'list' to display the command list. [Hello!] List of commands: * exit [-h] * hello [-h] [--name NAME] * help [-h] * list [-h] [Hello!] \n""", ), "help_command": ( "help\n", """\ Welcome to the CLI interface of hello! Try: * 'help' to display the help message * 'list' to display the command list. [Hello!] Type 'help' to display this message. Type 'list' to display the command list. Type ' -h' to display the help message of . [Hello!] \n""", ), "exit_command": ( "exit\n", """\ Welcome to the CLI interface of hello! Try: * 'help' to display the help message * 'list' to display the command list. [Hello!] """, ), "wrong_command": ( "hellooo\n", """\ Welcome to the CLI interface of hello! Try: * 'help' to display the help message * 'list' to display the command list. [Hello!] Command 'hellooo' does not exist. [Hello!] \n""", ), } def make_cli(streams=None): async def say_hello(reader, writer, name=None): data = f"Hello {name}!" if name else "Hello!" writer.write(data.encode() + b"\n") parser = argparse.ArgumentParser(description="Say hello") parser.add_argument("--name", "-n", type=str) commands = {"hello": (say_hello, parser)} return AsynchronousCli(commands, streams, prog="hello") @pytest.mark.parametrize( "input_string, expected", list(testdata.values()), ids=list(testdata.keys()) ) @pytest.mark.asyncio async def test_async_cli(monkeypatch, input_string, expected): monkeypatch.setattr("sys.ps1", "[Hello!] ", raising=False) monkeypatch.setattr("sys.stdin", io.StringIO(input_string)) monkeypatch.setattr("sys.stderr", io.StringIO()) await make_cli().interact(stop=False) assert sys.stderr.getvalue() == expected vxgmichel-aioconsole-3df7872/tests/test_execute.py000066400000000000000000000160471471042674700224400ustar00rootroot00000000000000import io import asyncio import pytest from aioconsole import aexec, aeval from aioconsole.execute import compile_for_aexec # Helper async def coro(x): await asyncio.sleep(0) return x # Test data testdata = { "simple": ({}, "1+1", 2, {}), "affect": ({}, "a=1", None, {"a": 1}), "modify": ({"b": 1}, "b=2", None, {"b": 2}), "multiple": ({}, "c=3;d=4;5", 5, {"c": 3, "d": 4}), "async": ({"coro": coro}, "await coro(6)", 6, {"coro": coro}), "multiline string": ({}, '"""\n"""', "\n", {}), "splitted string": ({}, '"a\\\nb"', "ab", {}), } # Parametrized test for aexec @pytest.mark.parametrize( "local, code, expected_result, expected_local", list(testdata.values()), ids=list(testdata.keys()), ) @pytest.mark.asyncio async def test_aexec_exec_mode(local, code, expected_result, expected_local): stream = io.StringIO() await aexec(code, local=local, stream=stream) assert stream.getvalue() == "" assert local == expected_local @pytest.mark.parametrize( "local, code, expected_result, expected_local", list(testdata.values()), ids=list(testdata.keys()), ) @pytest.mark.asyncio async def test_aexec_single_mode(local, code, expected_result, expected_local): stream = io.StringIO() await aexec(compile_for_aexec(code, "test", "single"), local=local, stream=stream) if expected_result is None: assert stream.getvalue() == "" else: assert stream.getvalue().strip() == repr(expected_result) assert local.pop("_") == expected_result assert local == expected_local def test_invalid_compile_modes(): with pytest.raises(ValueError): compile_for_aexec("1\n", "test", "eval") with pytest.raises(ValueError): compile_for_aexec("1\n", "test", "unknown") @pytest.mark.asyncio async def test_incomplete_code(): with pytest.raises(SyntaxError): await aexec("(") @pytest.mark.asyncio async def test_missing_newline(): # Missing newline in "exec" mode is OK dct = {} await aexec("def f():\n return 1", dct) assert dct["f"]() == 1 await aexec("def g(): return 2", dct) assert dct["g"]() == 2 # Missing newline in "single" raises a SyntaxError with pytest.raises(SyntaxError): await aexec( compile_for_aexec( "def f():\n return 1", "test", "single", dont_imply_dedent=True ) ) # Test return and yield handling @pytest.mark.asyncio async def test_return_handling(): with pytest.raises(SyntaxError) as context: await aexec("return None, {}") assert context.value.msg == "'return' outside function" @pytest.mark.asyncio async def test_yield_handling(): with pytest.raises(SyntaxError) as context: await aexec("for i in range(5): yield i") assert context.value.msg == "'yield' outside function" @pytest.mark.asyncio async def test_yield_from_handling(): with pytest.raises(SyntaxError) as context: await aexec("yield from range(5)") assert context.value.msg == "'yield' outside function" @pytest.mark.asyncio async def test_correct(): await aexec("def x(): return") await aexec("async def x(): return") await aexec("def x(): yield") await aexec("async def x(): yield") def echo(x): """Sync function for aeval parameterized test.""" return x async def aecho(x): """Async function for aeval parameterized test.""" return echo(x) # Parametrized test with a variety of expressions @pytest.mark.asyncio @pytest.mark.parametrize( "expression, local", [ # Valid Simple Expressions ("1 + 2", None), ("sum([i * i for i in range(10)])", None), # Invalid Expressions ("def foo(): return 42", None), ("x = 1", None), ("x = 1\nx + 1", None), ("for i in range(10): pass", None), ("if True: pass", None), ("while True: break", None), ("try: pass\nexcept: pass", None), # Expressions Involving Undefined Variables ("undefined_variable", None), ("undefined_function()", None), # Expressions with Deliberate Errors ("1/0", None), ("open('nonexistent_file.txt')", None), # Lambda and Anonymous Functions ("(lambda x: x * 2)(5)", None), # Expressions with Built-in Functions ("len('test')", None), ("min([3, 1, 4, 1, 5, 9])", None), ("max([x * x for x in range(10)])", None), # Boolean and Conditional Expressions ("True and False", None), ("not True", None), # Boolean negation ("5 if True else 10", None), # String Manipulation ("'hello' + ' ' + 'world'", None), ("f'hello {42}'", None), # Complex List Comprehensions ("[x for x in range(5)]", None), ("[x * x for x in range(10) if x % 2 == 0]", None), # Expressions with Syntax Errors ("return 42", None), ("yield 5", None), # Test with await ("await aecho(5)", {"aecho": aecho, "echo": echo}), # Test invalid local ("...", []), ("...", "string_instead_of_dict"), ("...", 42), ("...", set()), ("...", ...), ("...", 1.5), ("...", object()), ("...", asyncio), ("...", lambda: ...), ("...", {"__result__": 99}), # Invalid expressions ("", None), (None, None), (0, None), ({}, None), (object(), None), (asyncio, None), (..., None), (lambda: ..., None), # Conflicting name in local ("x", {"x": 1, "__aeval_result__": 99}), ], ) async def test_aeval(expression, local): async def capture(func, *args, **kwargs): try: if asyncio.iscoroutinefunction(func): result = await func(*args, **kwargs) else: result = func(*args, **kwargs) except Exception as exc: return (type(exc), None) else: return (None, result) # Remove the await keyword from the expression for the synchronous evaluation sync_expression = ( expression.replace("await a", "") if isinstance(expression, str) else expression ) # Capture and compare the results of the synchronous and asynchronous evaluations sync_capture = await capture(eval, sync_expression, local) async_capture = await capture(aeval, expression, local) assert sync_capture == async_capture # Test calling an async function without awaiting it @pytest.mark.asyncio async def test_aeval_async_func_without_await(): expression = "asyncio.sleep(0)" local = {"asyncio": asyncio} result = await aeval(expression, local) assert asyncio.iscoroutine(result) await result @pytest.mark.asyncio async def test_aeval_valid_await_syntax(): expression = "await aecho(10)" local = {"aecho": aecho} result = await aeval(expression, local) assert result == 10 @pytest.mark.asyncio async def test_aeval_coro_in_local(): expression = "await coro" local = {"coro": aecho(10)} result = await aeval(expression, local) assert result == 10 vxgmichel-aioconsole-3df7872/tests/test_interact.py000066400000000000000000000140141471042674700225770ustar00rootroot00000000000000import io import os import platform import sys import signal import asyncio from unittest.mock import Mock from contextlib import contextmanager import pytest from aioconsole import interact from aioconsole.stream import NonFileStreamReader, NonFileStreamWriter @contextmanager def stdcontrol(monkeypatch): # PS1 monkeypatch.setattr("sys.ps1", "[Hello!]", raising=False) # Stdin control stdin_read, stdin_write = os.pipe() monkeypatch.setattr("sys.stdin", open(stdin_read)) writer = NonFileStreamWriter(open(stdin_write, "w")) # Stdout control monkeypatch.setattr(sys, "stdout", io.StringIO()) # Stderr control stderr_read, stderr_write = os.pipe() monkeypatch.setattr("sys.stderr", open(stderr_write, "w")) reader = NonFileStreamReader(open(stderr_read)) # Yield yield reader, writer # Check assert sys.stdout.getvalue() == "" async def assert_stream(stream, expected, loose=False): s = None if loose else "\n" for expected_line in expected.splitlines(): line = await stream.readline() assert expected_line.strip(s) == line.decode().strip(s) @pytest.fixture(params=["unix", "not-unix"]) async def signaling(request, monkeypatch): if request.param == "not-unix": event_loop = asyncio.get_running_loop() m = Mock(side_effect=NotImplementedError) monkeypatch.setattr(event_loop, "add_signal_handler", m) monkeypatch.setattr(event_loop, "remove_signal_handler", m) yield request.param @pytest.mark.asyncio async def test_interact_simple(monkeypatch): with stdcontrol(monkeypatch) as (reader, writer): banner = "A BANNER" writer.write("1+1\n") await writer.drain() writer.stream.close() await interact(banner=banner, stop=False) await assert_stream(reader, banner) await assert_stream(reader, sys.ps1 + "2") await assert_stream(reader, sys.ps1) @pytest.mark.asyncio async def test_interact_traceback(monkeypatch): with stdcontrol(monkeypatch) as (reader, writer): banner = "A BANNER" writer.write("1/0\n") await writer.drain() writer.stream.close() await interact(banner=banner, stop=False) # Check stderr await assert_stream(reader, banner) await assert_stream(reader, sys.ps1 + "Traceback (most recent call last):") # Skip 3 lines for _ in range(4 if sys.version_info >= (3, 11) else 3): await reader.readline() # Check stderr await assert_stream(reader, "ZeroDivisionError: division by zero") await assert_stream(reader, sys.ps1) @pytest.mark.asyncio async def test_interact_syntax_error(monkeypatch): with stdcontrol(monkeypatch) as (reader, writer): writer.write("a b\n") await writer.drain() writer.stream.close() banner = "A BANNER" await interact(banner=banner, stop=False) await assert_stream(reader, banner) # Skip line await reader.readline() await assert_stream(reader, " a b") if sys.version_info >= (3, 10, 0) and sys.version_info < (3, 10, 1): await assert_stream(reader, " ^^^", loose=True) else: await assert_stream(reader, " ^", loose=True) if ( sys.version_info >= (3, 10, 0) and sys.version_info < (3, 10, 1) or ( platform.python_implementation() == "PyPy" and sys.version_info >= (3, 9) and sys.version_info < (3, 10) ) ): await assert_stream( reader, "SyntaxError: invalid syntax. Perhaps you forgot a comma?" ) else: await assert_stream(reader, "SyntaxError: invalid syntax") await assert_stream(reader, sys.ps1) @pytest.mark.asyncio async def test_interact_keyboard_interrupt(monkeypatch, signaling): with stdcontrol(monkeypatch) as (reader, writer): # Start interaction banner = "A BANNER" task = asyncio.ensure_future(interact(banner=banner, stop=False)) # Wait for banner await assert_stream(reader, banner) # Send SIGINT if sys.platform == "win32": signal.getsignal(signal.SIGINT)(signal.SIGINT, None) else: os.kill(os.getpid(), signal.SIGINT) # Wait for ps1 await assert_stream(reader, sys.ps1) await assert_stream(reader, "KeyboardInterrupt") # Close stdin writer.stream.close() # Wait for interact to finish await assert_stream(reader, sys.ps1) await task # Test assert sys.stdout.getvalue() == "" @pytest.mark.asyncio async def test_broken_pipe(monkeypatch, signaling): with stdcontrol(monkeypatch) as (reader, writer): # Start interaction banner = "A BANNER" task = asyncio.ensure_future(interact(banner=banner, stop=False)) # Wait for banner await assert_stream(reader, banner) # Close stdin writer.stream.close() reader.stream.close() # Wait for interact to finish await task # Test assert sys.stdout.getvalue() == "" @pytest.mark.asyncio async def test_interact_multiple_indented_lines(monkeypatch): with stdcontrol(monkeypatch) as (reader, writer): banner = "A BANNER" writer.write("def x():\n print(1)\n print(2)\n\nx()\n") await writer.drain() writer.stream.close() await interact(banner=banner, stop=False) await assert_stream(reader, banner) await assert_stream(reader, sys.ps1 + sys.ps2 * 3 + sys.ps1 + "1\n2") @pytest.mark.asyncio async def test_interact_cancellation(monkeypatch): with stdcontrol(monkeypatch) as (reader, writer): banner = "A BANNER" task = asyncio.ensure_future(interact(banner=banner, stop=False)) # Wait for banner await assert_stream(reader, banner) task.cancel() with pytest.raises(asyncio.CancelledError): await task assert task.cancelled vxgmichel-aioconsole-3df7872/tests/test_server.py000066400000000000000000000040271471042674700222770ustar00rootroot00000000000000import io import asyncio import pytest from aioconsole import compat from aioconsole.server import start_console_server, print_server @pytest.mark.asyncio async def test_server(): server = await start_console_server(host="127.0.0.1", port=0, banner="test") address = server.sockets[0].getsockname() stream = io.StringIO() print_server(server, "test console", file=stream) expected = f"The test console is being served on 127.0.0.1:{address[1]}\n" assert stream.getvalue() == expected reader, writer = await asyncio.open_connection(*address) assert (await reader.readline()) == b"test\n" writer.write(b"1+1\n") assert (await reader.readline()) == b">>> 2\n" writer.write_eof() assert (await reader.readline()) == b">>> \n" writer.close() await writer.wait_closed() server.close() await server.wait_closed() @pytest.mark.asyncio async def test_uds_server(tmpdir_factory): path = str(tmpdir_factory.mktemp("uds") / "my_uds") # Not available on windows if compat.platform == "win32": with pytest.raises(ValueError): await start_console_server(path=path, banner="test") return server = await start_console_server(path=path, banner="test") stream = io.StringIO() print_server(server, "test console", file=stream) expected = f"The test console is being served on {path}\n" assert stream.getvalue() == expected address = server.sockets[0].getsockname() reader, writer = await asyncio.open_unix_connection(address) assert (await reader.readline()) == b"test\n" writer.write(b"1+1\n") assert (await reader.readline()) == b">>> 2\n" writer.write_eof() assert (await reader.readline()) == b">>> \n" writer.close() await writer.wait_closed() server.close() await server.wait_closed() @pytest.mark.asyncio async def test_invalid_server(): with pytest.raises(ValueError): await start_console_server() with pytest.raises(ValueError): await start_console_server(path="uds", port=0) vxgmichel-aioconsole-3df7872/tests/test_stream.py000066400000000000000000000161571471042674700222730ustar00rootroot00000000000000import os import io import gc import sys import pytest import asyncio from unittest.mock import Mock from aioconsole.stream import create_standard_streams, ainput, aprint from aioconsole.stream import is_pipe_transport_compatible, get_standard_streams @pytest.mark.skipif(sys.platform == "win32", reason="Not supported on windows") @pytest.mark.asyncio async def test_create_standard_stream_with_pipe(is_uvloop): r1, w1 = os.pipe() r2, w2 = os.pipe() stdin = open(r1) stdout = open(w1, "w") stderr = open(w2, "w") assert is_pipe_transport_compatible(stdin) assert is_pipe_transport_compatible(stdout) assert is_pipe_transport_compatible(stderr) reader, writer1, writer2 = await create_standard_streams(stdin, stdout, stderr) writer1.write("a\n") await writer1.drain() data = await reader.readline() assert data == b"a\n" writer2.write("b\n") await writer2.drain() assert os.read(r2, 2) == b"b\n" # Mock stdout.close() to check if it has been called stdout_actual_close = stdout.close stdout.close = Mock() # Close the transport and delete the object writer1.transport.close() del reader, writer1, writer2 gc.collect() # Force garbage collection - necessary for pypy # Check that the transport has been closed but not stdout assert not stdout.close.called # Weirdly enough, uvloop DID close the file descriptor. # Probably because it used the file descriptor directly instead # of the pipe object. However, this should not be an issue since # file descriptors 0, 1, 2 do not seem to be affected by this. if not is_uvloop: stdout_actual_close() @pytest.mark.asyncio async def test_create_standard_stream_with_non_pipe(monkeypatch): stdin = io.StringIO("a\nb\nc\nd\n") stdout = io.StringIO() stderr = io.StringIO() reader, writer1, writer2 = await create_standard_streams(stdin, stdout, stderr) writer1.write("a\n") await writer1.drain() data = await reader.readline() assert data == b"a\n" assert stdout.getvalue() == "a\n" writer2.write("b\n") await writer2.drain() data = await reader.readline() assert data == b"b\n" assert stderr.getvalue() == "b\n" # Multiple writes writer2.write("c\n") writer2.write("d\n") await asyncio.sleep(0.1) writer2.write("e\n") writer2.close() assert writer2.is_closing() await writer2.wait_closed() assert stderr.getvalue() == "b\nc\nd\ne\n" with pytest.raises(RuntimeError): writer2.write("f\n") data = await reader.read(2) assert data == b"c\n" assert reader.at_eof() is False async for data in reader: assert data == b"d\n" assert reader.at_eof() is True # Check exception handling in the daemon thread class KeyboardInterruptLike(BaseException): pass def raise_keyboard_interrupt(*args): raise KeyboardInterruptLike def raise_os_error(*args): raise OSError monkeypatch.setattr(stdin, "readline", raise_os_error) with pytest.raises(OSError): data = await reader.readline() monkeypatch.setattr(stdin, "read", raise_keyboard_interrupt) with pytest.raises(KeyboardInterruptLike): data = await reader.read() def mock_stdio(monkeypatch, input_text="", disable_stdin=False): monkeypatch.setattr("sys.stdin", None if disable_stdin else io.StringIO(input_text)) monkeypatch.setattr("sys.stdout", io.StringIO()) monkeypatch.setattr("sys.stderr", io.StringIO()) @pytest.mark.asyncio async def test_ainput_with_standard_stream(monkeypatch): mock_stdio(monkeypatch, "a\nb\n") assert (await ainput()) == "a" assert (await ainput(">>> ")) == "b" assert sys.stdout.getvalue() == ">>> " assert sys.stderr.getvalue() == "" @pytest.mark.asyncio async def test_aprint_with_standard_stream(monkeypatch): mock_stdio(monkeypatch) await aprint("ab", "cd") assert sys.stdout.getvalue() == "ab cd\n" await aprint("a" * 1024 * 64) assert sys.stdout.getvalue() == "ab cd\n" + "a" * 1024 * 64 + "\n" assert sys.stderr.getvalue() == "" @pytest.mark.parametrize("flush", [False, True]) @pytest.mark.asyncio async def test_aprint_flush_argument(monkeypatch, flush): mock_stdio(monkeypatch) await aprint("a", flush=flush) if not flush: # Might or might not be there yet, depending on internal logic assert sys.stdout.getvalue() in ("", "a\n") await aprint("", end="", flush=True) assert sys.stdout.getvalue() == "a\n" @pytest.mark.asyncio async def test_read_from_closed_pipe(is_uvloop): if is_uvloop: pytest.skip("This test is flaky with uvloop for some reason.") stdin_r, stdin_w = os.pipe() stdout_r, stdout_w = os.pipe() stderr_r, stderr_w = os.pipe() stdin = open(stdin_w, "wb") stdin.write(b"hello\n") stdin.close() f_stdin = open(stdin_r, "r") f_stdout = open(stdout_w, "w") f_stderr = open(stderr_w, "w") reader, writer1, writer2 = await create_standard_streams( f_stdin, f_stdout, f_stderr ) result = await ainput(">>> ", streams=(reader, writer1)) assert result == "hello" writer1.close() await writer1.wait_closed() f_stdout.close() writer2.close() await writer2.wait_closed() f_stderr.close() assert open(stdout_r).read() == ">>> " assert open(stderr_r).read() == "" @pytest.mark.skipif(sys.platform == "win32", reason="Not supported on windows") @pytest.mark.asyncio async def test_standard_stream_pipe_buffering(is_uvloop): if is_uvloop: pytest.skip("This test is flaky with uvloop for some reason.") r1, w1 = os.pipe() r2, w2 = os.pipe() stdin = open(r1) stdout = open(w1, "w") stderr = open(w2, "w") assert is_pipe_transport_compatible(stdin) assert is_pipe_transport_compatible(stdout) assert is_pipe_transport_compatible(stderr) reader, writer1, writer2 = await create_standard_streams(stdin, stdout, stderr) blob_size = 4 * 1024 * 1024 # 4 MB writer1.write("a\n" + "b" * blob_size + "\n") task = asyncio.ensure_future(writer1.drain()) data = await reader.readline() assert data == b"a\n" # Check back pressure await asyncio.sleep(0.1) assert not task.done() assert len(reader._buffer) < blob_size data = await reader.readline() assert data == b"b" * blob_size + b"\n" await task @pytest.mark.asyncio async def test_aprint_with_no_stdin(monkeypatch): mock_stdio(monkeypatch, disable_stdin=True) await aprint("test1") assert sys.stdout.getvalue() == "test1\n" assert sys.stderr.getvalue() == "" with pytest.raises(RuntimeError) as ctx: await ainput("test2") assert str(ctx.value) == "ainput(): lost sys.stdin" assert sys.stdout.getvalue() == "test1\ntest2" assert sys.stderr.getvalue() == "" # Test the methods specifically reader, _ = await get_standard_streams() with pytest.raises(RuntimeError) as ctx: await reader.read(10) assert str(ctx.value) == "ainput(): lost sys.stdin" with pytest.raises(RuntimeError) as ctx: await reader.readline() assert str(ctx.value) == "ainput(): lost sys.stdin"