Add exit to repl

This commit is contained in:
Tim Van Baak 2020-01-01 18:10:21 -08:00
parent b57631d052
commit 04db9a020f
1 changed files with 12 additions and 4 deletions

View File

@ -1,21 +1,24 @@
# Standard library imports # Standard library imports
import argparse import argparse
import os
import traceback import traceback
# Application imports # Module imports
import cli import cli
import configs import configs
@cli.no_argument
def repl(args): def repl(args):
"""Runs a REPL with the given lexicon""" """Runs a REPL with the given lexicon"""
# Get all the cli commands' descriptions and add help and exit.
commands = { commands = {
name[8:]: func.__doc__ for name, func in vars(cli).items() name[8:]: func.__doc__ for name, func in vars(cli).items()
if name.startswith("command_")} if name.startswith("command_")}
commands['help'] = "Print this message" commands['help'] = "Print this message"
commands['exit'] = "Exit"
print("Amanuensis running on Lexicon {}".format(args.lexicon)) print("Amanuensis running on Lexicon {}".format(args.lexicon))
while True: while True:
# Read input in a loop.
try: try:
data = input("{}> ".format(args.lexicon)) data = input("{}> ".format(args.lexicon))
except EOFError: except EOFError:
@ -30,7 +33,12 @@ def repl(args):
print("Available commands:") print("Available commands:")
for name, func in commands.items(): for name, func in commands.items():
print(" {}: {}".format(name, func)) print(" {}: {}".format(name, func))
elif data.strip() == "exit":
print()
break
elif data.strip(): elif data.strip():
# Execute the command by appending it to the argv the
# REPL was invoked with.
try: try:
argv = sys.argv[1:] + data.split() argv = sys.argv[1:] + data.split()
main(argv) main(argv)
@ -64,9 +72,9 @@ def get_parser(valid_commands):
# command_ functions perform setup or execution depending on # command_ functions perform setup or execution depending on
# whether their argument is an ArgumentParser. # whether their argument is an ArgumentParser.
for name, func in valid_commands.items(): for name, func in valid_commands.items():
# Create the subparser. # Create the subparser, set the docstring as the description.
cmd = subp.add_parser(name, description=func.__doc__) cmd = subp.add_parser(name, description=func.__doc__)
# Delegate subparser setup. # Delegate subparser setup to the command.
func(cmd) func(cmd)
# Store function for later execution. # Store function for later execution.
cmd.set_defaults(func=func) cmd.set_defaults(func=func)