Reputation: 136
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.
Upvotes: 4
Views: 4032
Reputation: 472
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
Upvotes: 0
Reputation: 15388
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 theArgumentParser
will 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
Upvotes: 6