解析Python命令行参数最简单、最简洁、最灵活的方法或库是什么?


当前回答

我认为大型项目的最佳方法是optparse,但如果您正在寻找一种简单的方法,也许http://werkzeug.pocoo.org/documentation/script适合您。

from werkzeug import script

# actions go here
def action_foo(name=""):
    """action foo does foo"""
    pass

def action_bar(id=0, title="default title"):
    """action bar does bar"""
    pass

if __name__ == '__main__':
    script.run()

所以基本上每个函数action_*都暴露在命令行和一个nice 免费生成帮助信息。

python foo.py 
usage: foo.py <action> [<options>]
       foo.py --help

actions:
  bar:
    action bar does bar

    --id                          integer   0
    --title                       string    default title

  foo:
    action foo does foo

    --name                        string

其他回答

我更喜欢optparse而不是getopt。它非常具有声明性:您告诉它选项的名称和它们应该具有的效果(例如,设置一个布尔字段),它会返回给您一个根据您的规范填充的字典。

http://docs.python.org/lib/module-optparse.html

以防万一,如果你需要在Win32 (2K, XP等)上获取unicode参数,这可能会有所帮助:


from ctypes import *

def wmain(argc, argv):
    print argc
    for i in argv:
        print i
    return 0

def startup():
    size = c_int()
    ptr = windll.shell32.CommandLineToArgvW(windll.kernel32.GetCommandLineW(), byref(size))
    ref = c_wchar_p * size.value
    raw = ref.from_address(ptr)
    args = [arg for arg in raw]
    windll.kernel32.LocalFree(ptr)
    exit(wmain(len(args), args))
startup()

我认为大型项目的最佳方法是optparse,但如果您正在寻找一种简单的方法,也许http://werkzeug.pocoo.org/documentation/script适合您。

from werkzeug import script

# actions go here
def action_foo(name=""):
    """action foo does foo"""
    pass

def action_bar(id=0, title="default title"):
    """action bar does bar"""
    pass

if __name__ == '__main__':
    script.run()

所以基本上每个函数action_*都暴露在命令行和一个nice 免费生成帮助信息。

python foo.py 
usage: foo.py <action> [<options>]
       foo.py --help

actions:
  bar:
    action bar does bar

    --id                          integer   0
    --title                       string    default title

  foo:
    action foo does foo

    --name                        string

几乎每个人都在使用getopt

下面是文档的示例代码:

import getopt, sys

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError:
        # print help information and exit:
        usage()
        sys.exit(2)
    output = None
    verbose = False
    for o, a in opts:
        if o == "-v":
            verbose = True
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        if o in ("-o", "--output"):
            output = a

总之,这就是它的工作原理。

你有两种选择。一种是接受辩论的,另一种是接受辩论的 就像开关一样。

sys。argv基本上就是你C语言中的char** argv。就像在C语言中,你跳过第一个元素,也就是你程序的名字,只解析参数:

Getopt。Getopt将根据参数中给出的规则解析它。

这里的"ho:v"描述了短参数:- onletter。:表示-o接受一个参数。

最后["help", "output="]描述长参数(——morethanonletter)。 输出后的=再次表示输出接受一个参数。

结果是一对(选项,参数)的列表

如果一个选项不接受任何参数(比如help), arg部分就是一个空字符串。 然后,您通常希望在此列表上进行循环,并像示例中那样测试选项名称。

我希望这对你有所帮助。

Argparse代码可能比实际实现代码还要长!

这是我在大多数流行参数解析选项中发现的一个问题,如果您的参数只是适度的,那么用于记录它们的代码就会变得与它们所提供的好处不成比例地大。

对参数解析场景来说(我认为)一个相对的新来者是plac。

它与argparse做了一些公认的权衡,但使用内联文档并简单地包装main()类型函数:

def main(excel_file_path: "Path to input training file.",
     excel_sheet_name:"Name of the excel sheet containing training data including columns 'Label' and 'Description'.",
     existing_model_path: "Path to an existing model to refine."=None,
     batch_size_start: "The smallest size of any minibatch."=10.,
     batch_size_stop:  "The largest size of any minibatch."=250.,
     batch_size_step:  "The step for increase in minibatch size."=1.002,
     batch_test_steps: "Flag.  If True, show minibatch steps."=False):
"Train a Spacy (http://spacy.io/) text classification model with gold document and label data until the model nears convergence (LOSS < 0.5)."

    pass # Implementation code goes here!

if __name__ == '__main__':
    import plac; plac.call(main)