Possible Duplicate:
What's the best way to grab/parse command line arguments passed to a Python script?
I would like to be able to parse command line arguments in my Python 2.6 program.
Ideally, I want to be able to handle these cases:
# Show some help
./myprogram --help
# These are equivalent
./myprogram --block=1
./myprogram -b 1
# This means verbose, and twice as verbose:
./myprogram -v
./myprogram -vv
argparse — parse the arguments. Using argparse is how you let the user of your program provide values for variables at runtime. It's a means of communication between the writer of a program and the user. That user might be your future self.
The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present.
The standard Python library argparse used to incorporate the parsing of command line arguments. Instead of having to manually set variables inside of the code, argparse can be used to add flexibility and reusability to your code by allowing user input values to be parsed and utilized.
Check out the argparse module (or optparse for older Python versions).
Note that argparse
/optparse
are newer, better replacements for getopt
, so if you're new to this they're the recommended option. From the getopt
docs:
Note The getopt module is a parser for command line options whose API is designed to be familiar to users of the C getopt() function. Users who are unfamiliar with the C getopt() function or who would like to write less code and get better help and error messages should consider using the argparse module instead.
Python has argument processing built in, with the getopt
module.
It can handle long and short forms of arguments as well as "naked" and parameterised versions (--help
versus --num=7
).
For your specific use cases (with a little more), you'd probably be looking at something like:
opts,args = getopt.getopt(argv,"b:vVh",["block=", "verbose", "very-verbose", "help"])
I'm not sure off the top of my head if it allows multi-character single-hyphen variants like -vv
. I'd just use -v
and -V
myself to make my life easier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With