开发者

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

开发者 https://www.devze.com 2023-01-06 18:46 出处:网络
This question already has answers here: Closed 11 ye开发者_如何学运维ars ago. Possible Duplicate:
This question already has answers here: Closed 11 ye开发者_如何学运维ars ago.

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


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.


optfunc is an interesting little module. It's great if you want to quickly write a little script. For larger things I would go with argparse as others wrote.


A better option than that link is the modules OptParse or GetOpt, and depending on which version of Python you're using, the newest ones..2.7, and 3.1.2, have an even newer module built in. The documentation on the official python.org reference has a very informative set of documentation and examples for those modules. If you go to python.org and just do a quick search for OptParse or GetOpt, you'll have everything you need.


There might be a better way but I would just uses sys.argv and put in conditionals wherever needed i.e.

if '--v' or '--vv' in sys.argv :
    print 'verbose message'
0

精彩评论

暂无评论...
验证码 换一张
取 消