I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments.
What are some of the ways Python programmers can do this?
I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments.
What are some of the ways Python programmers can do this?
The canonical solution in the standard library is
argparse
(docs):Here is an example:
argparse
supports (among other things):As you can see optparse "The optparse module is deprecated with and will not be developed further; development will continue with the argparse module."
Yet another option is argh. It builds on argparse, and lets you write things like:
It will automatically generate help and so on, and you can use decorators to provide extra guidance on how the arg-parsing should work.
I recommend looking at docopt as a simple alternative to these others.
docopt is a new project that works by parsing your --help usage message rather than requiring you to implement everything yourself. You just have to put your usage message in the POSIX format.
I like getopt from stdlib, eg:
Lately I have been wrapping something similiar to this to make things less verbose (eg; making "-h" implicit).
Just going around evangelizing for argparse which is better for these reasons.. essentially:
(copied from the link)
argparse module can handle positional and optional arguments, while optparse can handle only optional arguments
argparse isn’t dogmatic about what your command line interface should look like - options like -file or /file are supported, as are required options. Optparse refuses to support these features, preferring purity over practicality
argparse produces more informative usage messages, including command-line usage determined from your arguments, and help messages for both positional and optional arguments. The optparse module requires you to write your own usage string, and has no way to display help for positional arguments.
argparse supports action that consume a variable number of command-line args, while optparse requires that the exact number of arguments (e.g. 1, 2, or 3) be known in advance
argparse supports parsers that dispatch to sub-commands, while optparse requires setting
allow_interspersed_args
and doing the parser dispatch manuallyAnd my personal favorite:
add_argument()
to be specified with simple callables, while optparse requires hacking class attributes likeSTORE_ACTIONS
orCHECK_METHODS
to get proper argument checking