Skip to content

Commit

Permalink
Merge f33a7e0 into c3c7be8
Browse files Browse the repository at this point in the history
  • Loading branch information
vxgmichel committed Mar 16, 2020
2 parents c3c7be8 + f33a7e0 commit a0cf7ac
Show file tree
Hide file tree
Showing 14 changed files with 53 additions and 35 deletions.
3 changes: 2 additions & 1 deletion .travis.yml
Expand Up @@ -7,7 +7,8 @@ python:
- pypy3.5
- 3.6
- 3.7
- 3.8-dev
- 3.8
- 3.9-dev

matrix:
include:
Expand Down
2 changes: 1 addition & 1 deletion aioconsole/__init__.py
Expand Up @@ -4,7 +4,7 @@
"""

from .execute import aexec
from .code import AsynchronousConsole, interact
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
Expand Down
8 changes: 4 additions & 4 deletions aioconsole/apython.py
Expand Up @@ -35,14 +35,14 @@ def exec_pythonstartup(locals_dict):
try:
locals_dict['__file__'] = filename
exec(startupcode, globals(), locals_dict)
except Exception as e: # pragma: no cover
tb = traceback.format_exc()
print(tb)
except Exception: # pragma: no cover
traceback.print_exc()
finally:
locals_dict.pop('__file__', None)

else:
print('Could not open PYTHONSTARTUP - No such file: {}'.format(filename))
message = 'Could not open PYTHONSTARTUP - No such file: {}'
print(message.format(filename))


def parse_args(args=None):
Expand Down
7 changes: 3 additions & 4 deletions aioconsole/command.py
@@ -1,15 +1,14 @@
"""Provide an asynchronous equivalent to the python console."""

import sys
import random
import asyncio
import argparse
import shlex

from . import code
from . import console


class AsynchronousCli(code.AsynchronousConsole):
class AsynchronousCli(console.AsynchronousConsole):

def __init__(self, commands, streams=None, *, prog=None,
prompt_control=None, loop=None):
Expand Down Expand Up @@ -97,7 +96,7 @@ def runsource(self, source, filename=None):
raise

# Prompt the traceback or result
except:
except BaseException:
self.showtraceback()
else:
if result is not None:
Expand Down
9 changes: 7 additions & 2 deletions aioconsole/code.py → aioconsole/console.py
Expand Up @@ -20,6 +20,11 @@
Try: {0} asyncio.sleep(1, result=3)
---""".format('await' if compat.PY35 else 'yield from')

# cx_Freeze does not include the help function
try:
help_function = help
except NameError:
help_function = None

current_task = (
asyncio.current_task if compat.PY37 else asyncio.Task.current_task)
Expand Down Expand Up @@ -64,7 +69,7 @@ def print(self, *args, **kwargs):
kwargs.setdefault('file', self)
print(*args, **kwargs)

@functools.wraps(help)
@functools.wraps(help_function)
def help(self, obj):
self.print(pydoc.render_doc(obj))

Expand Down Expand Up @@ -107,7 +112,7 @@ def runcode(self, code):
yield from execute.aexec(code, self.locals, self)
except SystemExit:
raise
except:
except BaseException:
self.showtraceback()
yield from self.flush()

Expand Down
5 changes: 2 additions & 3 deletions aioconsole/events.py
Expand Up @@ -3,15 +3,14 @@
import asyncio
import functools

from . import code
from . import compat
from . import server
from . import console


class InteractiveEventLoop(asyncio.SelectorEventLoop):
"""Event loop running a python console."""

console_class = code.AsynchronousConsole
console_class = console.AsynchronousConsole

def __init__(self, *, selector=None, locals=None, banner=None, serve=None,
prompt_control=None):
Expand Down
2 changes: 1 addition & 1 deletion aioconsole/rlwrap.py
Expand Up @@ -113,7 +113,7 @@ def write(arg):
def input(prompt='', use_stderr=False):
# Use readline if possible
try:
import readline
import readline # noqa
except ImportError:
return builtins.input(prompt)
# Use stdout
Expand Down
6 changes: 3 additions & 3 deletions aioconsole/server.py
Expand Up @@ -4,7 +4,7 @@
import socket
from functools import partial

from . import code
from . import console


@asyncio.coroutine
Expand All @@ -17,7 +17,7 @@ def handle_connect(reader, writer, factory, banner=None):


@asyncio.coroutine
def start_interactive_server(factory=code.AsynchronousConsole,
def start_interactive_server(factory=console.AsynchronousConsole,
host=None, port=None, path=None,
banner=None, *, loop=None):
if (port is None) == (path is None):
Expand All @@ -39,7 +39,7 @@ def start_console_server(host=None, port=None, path=None,
locals=None, filename="<console>", banner=None,
prompt_control=None, *, loop=None):
factory = partial(
code.AsynchronousConsole,
console.AsynchronousConsole,
locals=locals, filename=filename, prompt_control=prompt_control)
server = yield from start_interactive_server(
factory,
Expand Down
29 changes: 18 additions & 11 deletions aioconsole/stream.py
Expand Up @@ -36,22 +36,21 @@ def protect_standard_streams(stream):


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):
if self._stream_reader is not None:
if exc is None:
self._stream_reader.feed_eof()
else:
self._stream_reader.set_exception(exc)
if not self._closed.done():
if exc is None:
self._closed.set_result(None)
else:
self._closed.set_exception(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):
Expand Down Expand Up @@ -199,7 +198,15 @@ def ainput(prompt='', *, streams=None, use_stderr=False, loop=None):


@asyncio.coroutine
def aprint(*values, sep=None, end='\n', flush=False, streams=None, use_stderr=False, loop=None):
def aprint(
*values,
sep=None,
end='\n',
flush=False,
streams=None,
use_stderr=False,
loop=None
):
"""Asynchronous equivalent to *print*."""
# Get standard streams
if streams is None:
Expand Down
1 change: 1 addition & 0 deletions example/cli.py
Expand Up @@ -68,5 +68,6 @@ def main(args=None):
asyncio.ensure_future(make_cli().interact())
return echo.run(host, port)


if __name__ == '__main__':
main()
1 change: 1 addition & 0 deletions example/echo.py
Expand Up @@ -34,6 +34,7 @@ def main(args):
host, port = server.split(':')
return run(host, int(port))


if __name__ == '__main__':
import sys
main(sys.argv)
6 changes: 5 additions & 1 deletion tests/test_apython.py
Expand Up @@ -28,11 +28,13 @@ def hehe():
'''


@pytest.fixture
def tempfd():
with tempfile.NamedTemporaryFile() as tf:
yield tf


@contextmanager
def mock_module(name):
try:
Expand Down Expand Up @@ -181,7 +183,8 @@ def test_apython_non_existing_file(capfd):
apython.run_apython(['idontexist.py'])
out, err = capfd.readouterr()
assert out == ''
assert "No such file or directory: 'idontexist.py'" in err
assert "No such file or directory" in err
assert "idontexist.py" in err


def test_apython_non_existing_module(capfd):
Expand All @@ -191,6 +194,7 @@ def test_apython_non_existing_module(capfd):
assert out == ''
assert "No module named idontexist" in err


def test_apython_pythonstartup(capfd, use_readline, monkeypatch, tempfd):

monkeypatch.setenv('PYTHONSTARTUP', tempfd.name)
Expand Down
5 changes: 3 additions & 2 deletions tests/test_interact.py
Expand Up @@ -36,8 +36,9 @@ def stdcontrol(event_loop, monkeypatch):
@asyncio.coroutine
def assert_stream(stream, expected, loose=False):
s = None if loose else "\n"
for line in expected.splitlines():
assert line.strip(s) == (yield from stream.readline()).decode().strip(s)
for expected_line in expected.splitlines():
line = yield from stream.readline()
assert expected_line.strip(s) == line.decode().strip(s)


@pytest.fixture(params=['unix', 'not-unix'])
Expand Down
4 changes: 2 additions & 2 deletions tests/test_stream.py
Expand Up @@ -76,7 +76,7 @@ def test_create_standard_stream_with_non_pipe():
data = yield from reader.read(2)
assert data == b'c\n'

assert reader.at_eof() == False
assert reader.at_eof() is False

if compat.PY35:
assert (yield from reader.__aiter__()) == reader
Expand All @@ -87,7 +87,7 @@ def test_create_standard_stream_with_non_pipe():
assert (yield from reader.read()) == b'd\n'
assert (yield from reader.read()) == b''

assert reader.at_eof() == True
assert reader.at_eof() is True


@pytest.mark.asyncio
Expand Down

0 comments on commit a0cf7ac

Please sign in to comment.