Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse command line arguments in Python? [duplicate]

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
like image 674
Jerub Avatar asked Jul 13 '10 04:07

Jerub


People also ask

What is arg parsing?

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.

What is Store_true in Python?

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.

What is parser Add_argument in Python?

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.


2 Answers

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.

like image 107
tzaman Avatar answered Sep 23 '22 18:09

tzaman


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.

like image 27
paxdiablo Avatar answered Sep 22 '22 18:09

paxdiablo