Reputation: 2093
I've got a command line interface for a Python program that has a bunch of options (say, --a
, --b
, --c
) but one switches between commands with other switches.
So, perhaps prog -S a b c
invokes the -S
action, and prog -Y a b c
invokes the -Y
action. prog -Y a b c --a=2 --b=3
, then, should invoke the -Y
action with parameters a
and b
and positional argument a
, b
, c
Is there any way to make argparse
or getopt
do the argument parsing for me? Is there some other library to do this nicely?
Upvotes: 1
Views: 126
Reputation: 11
I'm not entirely sure if this will help, but so far, I have been writing a wrapper that takes arguments from XML set by a web interface, and then passes them into the command:
Obviously takes more complicated argument strings, but for the sake of an example:
def __main__():
parser = optparse.OptionParser()
parser.add_option( '-Q', '--ibmax', dest='ibmax', help='' )
(options, args) = parser.parse_args()
if options.ibmax != 'None' and int( options.ibmax ) >= 1:
ibmax = '--bmax %s' % options.ibmax
cmd1 = Popen([another.py, '-Q "%s"' % (options.ibmax),], stdout=PIPE).communicate()[0]
process = subprocess.Popen(cmd1, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Depending on certain flags in my web interface, more options are added to the arg list and thus a different command is run. Add every command option to the parser and then check the value of the -Y or -S command to set vars and change which command you need to pass.
I hope this helps, I'm no python pro, this just works for me.
Upvotes: 1
Reputation: 40374
I think using argparse's subcommands would be useful in this case.
Basically you can create a main parser that takes care of the parsing of the subcommand together with some common general options and then a few subparsers (one for each subcommand) that take care of the parsing of the specific options passed to the subcommands.
Upvotes: 3