I am making a terminal game using Python's wonderful Cmd library. But i was curious if i could somehow put argparse code into it. Like use argparse to handle the 'args' from my cmd.Cmd() class. To do this, i was really hoping that argparse had a way to manually pass args into it. I skimmed over the docs, but didn't notice anything like that.
2 Answers
parse_args() takes an optional argument args with a list (or tuple) of to parse. parse_args() (without arguments) is equivalent to parse_args(sys.argv[1:]):
In a script,
parse_args()will typically be called with no arguments, and theArgumentParserwill automatically determine the command-line arguments fromsys.argv.
If you do not have a tuple, but a single string, shell-like argument splitting can be accomplished using shlex.split()
>>> shlex.split('"A" B C\\ D')
['A', 'B', 'C D']
Note that argparse will print usage and help messages as well as exit() on fatal errors. You can override .error() to handle errors yourself:
class ArgumentParserNoExit(argparse.ArgumentParser):
def error(self, message):
raise ValueError(message) # or whatever you like
3 Comments
except the error the user will still see the error, but the script wont crash.argparse will also exit() on fatal errors. Override .error() on the parser to fix that..error() can i not just except SystemExit: pass? It's a game - I don't want it to crash everytime players typo a command in Cmd()You could also try namedtuple to manually provide the input arguments,
from collections import namedtuple
ManualInput = namedtuple("ManualInput", ["arg1", "arg2"])
args = ManualInput(1, 4)
you will get
In [1]: print(args.arg2)
Out[1]: 4
parse_args(args)?sys.argv.parse_args()is equal toparse_args(sys.argv). If you want to pass a single shell-like string (with quoting), you might want to useshlex.split(), first.shlex?