Skip to content

Commit

Permalink
Use black formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
vxgmichel committed Jun 10, 2020
1 parent 742d0c2 commit 5c26c77
Show file tree
Hide file tree
Showing 20 changed files with 466 additions and 469 deletions.
20 changes: 15 additions & 5 deletions aioconsole/__init__.py
Expand Up @@ -12,8 +12,18 @@
from .server import start_interactive_server
from .apython import run_apython

__all__ = ['aexec', 'ainput', 'aprint', 'AsynchronousConsole', 'interact',
'InteractiveEventLoop', 'InteractiveEventLoopPolicy',
'set_interactive_policy', 'run_console',
'AsynchronousCli', 'start_interactive_server',
'get_standard_streams', 'run_apython']
__all__ = [
"aexec",
"ainput",
"aprint",
"AsynchronousConsole",
"interact",
"InteractiveEventLoop",
"InteractiveEventLoopPolicy",
"set_interactive_policy",
"run_console",
"AsynchronousCli",
"start_interactive_server",
"get_standard_streams",
"run_apython",
]
1 change: 1 addition & 0 deletions aioconsole/__main__.py
@@ -1,2 +1,3 @@
from .apython import run_apython

run_apython()
91 changes: 47 additions & 44 deletions aioconsole/apython.py
Expand Up @@ -12,7 +12,7 @@
from . import rlwrap
from . import compat

ZERO_WIDTH_SPACE = '\u200b'
ZERO_WIDTH_SPACE = "\u200b"

DESCRIPTION = """\
Run the given python file or module with a modified asyncio policy replacing
Expand All @@ -23,68 +23,72 @@
usage: apython [-h] [--serve [HOST:] PORT] [--no-readline]
[--banner BANNER] [--locals LOCALS]
[-m MODULE | FILE] ...
""".split('usage: ')[1]
""".split(
"usage: "
)[
1
]


def exec_pythonstartup(locals_dict):
filename = os.environ.get('PYTHONSTARTUP')
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
locals_dict["__file__"] = filename
exec(startupcode, globals(), locals_dict)
except Exception: # pragma: no cover
traceback.print_exc()
finally:
locals_dict.pop('__file__', None)
locals_dict.pop("__file__", None)

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


def parse_args(args=None):
parser = argparse.ArgumentParser(
prog='apython',
description=DESCRIPTION,
usage=USAGE)
prog="apython", description=DESCRIPTION, usage=USAGE
)

# Options

parser.add_argument(
'--serve', '-s', metavar='[HOST:] PORT',
help='serve a console on the given interface instead')
"--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')
"--no-readline",
dest="readline",
action="store_false",
help="disable readline support",
)
parser.add_argument("--banner", help="provide a custom banner")
parser.add_argument(
'--banner', help='provide a custom banner')
parser.add_argument(
'--locals', type=ast.literal_eval,
help='provide custom locals as a dictionary')
"--locals", type=ast.literal_eval, help="provide custom locals as a dictionary"
)

# Hidden option

parser.add_argument(
'--prompt-control', metavar='PC',
help=argparse.SUPPRESS)
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(
'-m', dest='module',
help='run a python module')
parser.add_argument(
'filename', metavar='FILE', nargs='?',
help='python file to run')
"filename", metavar="FILE", nargs="?", help="python file to run"
)

# Extra arguments

parser.add_argument(
'args', metavar='ARGS', nargs=argparse.REMAINDER,
help='extra arguments')
"args", metavar="ARGS", nargs=argparse.REMAINDER, help="extra arguments"
)

namespace = parser.parse_args(args)

Expand All @@ -102,8 +106,7 @@ def parse_args(args=None):
def run_apython(args=None):
namespace = parse_args(args)

if namespace.readline and not namespace.serve and \
compat.platform != 'win32':
if namespace.readline and not namespace.serve and compat.platform != "win32":

try:
import readline
Expand All @@ -122,15 +125,14 @@ def run_apython(args=None):
sys._path = sys.path
if namespace.module:
sys.argv = [None] + namespace.args
sys.path.insert(0, '')
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)
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))
Expand All @@ -139,9 +141,9 @@ def run_apython(args=None):
locals=namespace.locals,
banner=namespace.banner,
serve=namespace.serve,
prompt_control=namespace.prompt_control)
runpy.run_path(namespace.filename,
run_name='__main__')
prompt_control=namespace.prompt_control,
)
runpy.run_path(namespace.filename, run_name="__main__")
else:
if namespace.locals is None:
namespace.locals = {}
Expand All @@ -150,7 +152,8 @@ def run_apython(args=None):
locals=namespace.locals,
banner=namespace.banner,
serve=namespace.serve,
prompt_control=namespace.prompt_control)
prompt_control=namespace.prompt_control,
)
finally:
sys.argv = sys._argv
sys.path = sys._path
Expand All @@ -167,10 +170,10 @@ def run_apython_in_subprocess(args=None, prompt_control=None):
# Create subprocess
proc_args = [
sys.executable,
'-m', 'aioconsole',
'--no-readline',
'--prompt-control', prompt_control]
return rlwrap.rlwrap_process(
proc_args + args,
"-m",
"aioconsole",
"--no-readline",
"--prompt-control",
prompt_control,
use_stderr=True)
]
return rlwrap.rlwrap_process(proc_args + args, prompt_control, use_stderr=True)
51 changes: 26 additions & 25 deletions aioconsole/command.py
Expand Up @@ -8,32 +8,32 @@


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)
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.commands["help"] = (
self.help_command,
argparse.ArgumentParser(
description='Display the help message.'))
self.commands['list'] = (
argparse.ArgumentParser(description="Display the help message."),
)
self.commands["list"] = (
self.list_command,
argparse.ArgumentParser(
description='Display the command list.'))
self.commands['exit'] = (
argparse.ArgumentParser(description="Display the command list."),
)
self.commands["exit"] = (
self.exit_command,
argparse.ArgumentParser(
description='Exit the interface.'))
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)
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]
prog = self.prog or sys.argv[0].split("/")[-1]
msg = "Welcome to the CLI interface of {0}!\n".format(prog)
msg += "Try:\n"
msg += " * 'help' to display the help message\n"
Expand All @@ -47,20 +47,20 @@ async def help_command(self, reader, writer):
Type '<command> -h' to display the help message of <command>."""

async def list_command(self, reader, writer):
msg = 'List of commands:'
msg = "List of commands:"
for key, (corofunc, parser) in sorted(self.commands.items()):
usage = parser.format_usage().replace('usage: ', '')[:-1]
msg += '\n * ' + usage
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('\\'):
if source.strip().endswith("\\"):
return True
source = source.replace('\\\n', '')
source = source.replace("\\\n", "")
try:
name, *args = shlex.split(source)
except ValueError:
Expand All @@ -74,8 +74,9 @@ async def runsource(self, source, filename=None):
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)
parser._print_message = lambda message, file=None: message and self.write(
message
)

# Parse arguments
try:
Expand All @@ -95,6 +96,6 @@ async def runsource(self, source, filename=None):
self.showtraceback()
else:
if result is not None:
self.write(str(result) + '\n')
self.write(str(result) + "\n")
await self.flush()
return False

0 comments on commit 5c26c77

Please sign in to comment.