Add lexicon repl

This commit is contained in:
Tim Van Baak 2019-12-31 13:21:19 -08:00
parent 7f6035c0c2
commit e4e3e45217
1 changed files with 38 additions and 10 deletions

View File

@ -1,11 +1,42 @@
# Standard library imports
import argparse
import traceback
# Application imports
import cli
import configs
@cli.no_argument
def repl(args):
"""Runs a REPL with the given lexicon"""
commands = {
name[8:]: func.__doc__ for name, func in vars(cli).items()
if name.startswith("command_")}
commands['help'] = "Print this message"
print("Amanuensis running on Lexicon {}".format(args.lexicon))
while True:
try:
data = input("{}> ".format(args.lexicon))
except EOFError:
print()
break
tokens = data.strip().split()
if not data.strip():
pass
elif tokens[0] not in commands:
print("'{}' is not a valid command.".format(tokens[0]))
elif data.strip() == "help":
print("Available commands:")
for name, func in commands.items():
print(" {}: {}".format(name, func))
elif data.strip():
try:
argv = sys.argv[1:] + data.split()
main(argv)
except Exception as e:
traceback.print_exc()
def get_parser(valid_commands):
# Pull out the command functions' docstrings to describe them.
command_descs = "\n".join([
@ -16,14 +47,14 @@ def get_parser(valid_commands):
parser = argparse.ArgumentParser(
description="Available commands:\n{}\n".format(command_descs),
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("-n",
dest="lexicon",
parser.add_argument("lexicon",
metavar="LEXICON",
help="The name of the lexicon to operate on")
parser.add_argument("-v",
action="store_true",
dest="verbose",
help="Enable debug logging")
parser.set_defaults(func=lambda a: parser.print_help())
parser.set_defaults(func=repl)
subp = parser.add_subparsers(
metavar="COMMAND",
help="The command to execute")
@ -36,22 +67,19 @@ def get_parser(valid_commands):
cmd = subp.add_parser(name, description=func.__doc__)
# Delegate subparser setup.
func(cmd)
# Store function for later execution
# Store function for later execution.
cmd.set_defaults(func=func)
return parser
def no_command():
print("nothing")
def main():
def main(argv):
# Enumerate valid commands from the CLI module.
commands = {
name[8:] : func
for name, func in vars(cli).items()
if name.startswith("command_")}
args = get_parser(commands).parse_args()
args = get_parser(commands).parse_args(argv)
# Configure logging.
if args.verbose:
@ -62,4 +90,4 @@ def main():
if __name__ == "__main__":
import sys
sys.exit(main())
sys.exit(main(sys.argv[1:]))