简体   繁体   中英

Parsing arbitrary number of arguments in Python OptParser

How can I define an option with an arbitrary number of arguments in Python's OptParser?

I'd like something like:

python my_program.py --my-option X,Y  # one argument passed, "X,Y"

python my_prgoram.py --my-option X,Y  Z,W  # two arguments passed, "X,Y" and "Z,W"

the nargs= option of OptParser limits me to a defined number. How can I do something like this?

parser.add_option("--my-options", dest="my_options", action="append", nargs="*")

which will simply take whatever's after --my-option and put it into a list? Eg for case 1, it should be ["X,Y"], for case 2 it should be ["X,Y", "Z,W"].

What's a way to do this with OptParser?

thanks.

The optarse module is deprecated in python 2.7 (which has just been released!). If you can upgrade, then you can use its replacement the argparse module. I think that has what you want. It supports a '*' value for nargs .

http://docs.python.org/library/argparse.html#nargs

Have you tried ommitting the n_args bit? The examples in the docs suggest you don't need it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM