Currently my code looks like this. It allows me to parse multiple parameters my program script gets. Is there a different way that is closer to \'best practices\'? I haven\'t se
With the exception of --version
, which is very commonly an option, the actions you've provided are better off treated as "subcommands".
I'm unaware of the argparse specifics, as I have yet to try Python 2.7, but you might take a look at the svn
command as an example, here's some pseudocode for the command line:
myprog [--version] [...]
Where
in:
add|edit|getweather|post|custompost|list
And
are options specific to that command. Using optparse (which is similar), this would mean that your command would be returned in args
, when calling parse_args
, allowing you to do something like this:
opts, args = parser.parse_args()
if opts.version:
...
else:
getattr("do_" + args[0])(*args[1:])
I find this pattern particularly useful for debugging, where I'd provide access to internal functions from the command line, and pass various arguments for testing. Adjust the selection of the command handler as appropriate for your own project.