Skip to content

Commit

Permalink
cli: add support for passing command-line arguments to the REPL and s…
Browse files Browse the repository at this point in the history
…cript environments
  • Loading branch information
attie committed Oct 3, 2023
1 parent 17d59a8 commit 7e3f949
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
8 changes: 8 additions & 0 deletions examples/script_args.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import argparse

parser = argparse.ArgumentParser('script_args.py')
parser.add_argument('-m', '--my-arg', default=0, type=int)

my_args = parser.parse_args(args.script_args)

print(my_args)
2 changes: 1 addition & 1 deletion software/glasgow/applet/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def add_repl_arguments(cls, parser):

async def repl(self, device, args, iface):
self.logger.info("dropping to REPL; use 'help(iface)' to see available APIs")
await AsyncInteractiveConsole(locals={"device":device, "iface":iface},
await AsyncInteractiveConsole(locals={"device":device, "iface":iface, "args":args},
run_callback=device.demultiplexer.flush).interact()


Expand Down
11 changes: 10 additions & 1 deletion software/glasgow/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,12 @@ def add_applet_arg(parser, mode, required=False):
if mode == "tool":
applet_cls.tool_cls.add_arguments(p_applet)

if mode in ("repl", "script"):
# this will absorb all arguments from the '--' onwards (inclusive), make sure it's
# always last... the '--' item that ends up at the front is removed before the list
# is passed to the repo / script environment
p_applet.add_argument('script_args', nargs=argparse.REMAINDER)

parser = create_argparser()

def revision(arg):
Expand Down Expand Up @@ -621,6 +627,9 @@ async def run_applet():
logger.warn("applet %r is PREVIEW QUALITY and may CORRUPT DATA", args.applet)
try:
iface = await applet.run(device, args)
if args.action in ("repl", "script"):
if len(args.script_args) > 0 and args.script_args[0] == "--":
args.script_args = args.script_args[1:]
if args.action == "run":
return await applet.interact(device, args, iface)
elif args.action == "repl":
Expand All @@ -632,7 +641,7 @@ async def run_applet():
else:
code = compile(args.script_cmd, filename="<command>",
mode="exec", flags=PyCF_ALLOW_TOP_LEVEL_AWAIT)
future = eval(code, {"iface":iface, "device":device})
future = eval(code, {"iface":iface, "device":device, "args":args})
if future is not None:
await future

Expand Down

0 comments on commit 7e3f949

Please sign in to comment.