简体   繁体   中英

Command line options with optional arguments in Python

I was wondering if there's a simple way to parse command line options having optional arguments in Python. For example, I'd like to be able to call a script two ways:

> script.py --foo
> script.py --foo=bar

From the Python getopt docs it seems I have to choose one or the other.

另外,请注意标准库还有optparse ,一个功能更强大的选项解析器。

check out argparse: http://code.google.com/p/argparse/

especially the 'nargs' option

optparse module from stdlib doesn't support it out of the box (and it shouldn't due to it is a bad practice to use command-line options in such way).

As @Kevin Horn pointed out you can use argparse module (installable via easy_install argparse or just grab argparse.py and put it anywhere in your sys.path ).

Example

#!/usr/bin/env python
from argparse import ArgumentParser

if __name__ == "__main__":
    parser = ArgumentParser(prog='script.py')
    parser.add_argument('--foo', nargs='?', metavar='bar', default='baz')

    parser.print_usage()    
    for args in ([], ['--foo'], ['--foo', 'bar']):
        print "$ %s %s -> foo=%s" % (
            parser.prog, ' '.join(args).ljust(9), parser.parse_args(args).foo)

Output

usage: script.py [-h] [--foo [bar]]
$ script.py           -> foo=baz
$ script.py --foo     -> foo=None
$ script.py --foo bar -> foo=bar

There isn't an option in optparse that allows you to do this. But you can extend it to do it:

http://docs.python.org/library/optparse.html#adding-new-actions

使用optparse包。

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