简体   繁体   English

Python中带有可选参数的命令行选项

[英]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. 我想知道是否有一种简单的方法来解析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. 从Python getopt文档中我似乎必须选择其中一个。

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

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

especially the 'nargs' option 特别是'nargs'选项

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). 来自stdlib的optparse模块不支持开箱即用(并且不应该因为以这种方式使用命令行选项是不好的做法)。

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 ). 正如@Kevin Horn指出的那样你可以使用argparse模块(可以通过easy_install argparse安装,或者只需抓住argparse.py并将其放在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. optparse中没有允许您执行此操作的选项。 But you can extend it to do it: 但你可以扩展它来做到这一点:

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

使用optparse包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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