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


当前回答

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)

其他回答

我更喜欢点击。它抽象了管理选项,并允许“(…)以一种可组合的方式,用尽可能少的代码创建漂亮的命令行界面”。

下面是用法示例:

import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
              help='The person to greet.')
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo('Hello %s!' % name)

if __name__ == '__main__':
    hello()

它还会自动生成格式良好的帮助页面:

$ python hello.py --help
Usage: hello.py [OPTIONS]

  Simple program that greets NAME for a total of COUNT times.

Options:
  --count INTEGER  Number of greetings.
  --name TEXT      The person to greet.
  --help           Show this message and exit.

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

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

值得一提的是主机游戏。它很容易使用。看看吧:

from consoleargs import command

@command
def main(url, name=None):
  """
  :param url: Remote URL 
  :param name: File name
  """
  print """Downloading url '%r' into file '%r'""" % (url, name)

if __name__ == '__main__':
  main()

现在在控制台:

% python demo.py --help
Usage: demo.py URL [OPTIONS]

URL:    Remote URL 

Options:
    --name -n   File name

% python demo.py http://www.google.com/
Downloading url ''http://www.google.com/'' into file 'None'

% python demo.py http://www.google.com/ --name=index.html
Downloading url ''http://www.google.com/'' into file ''index.html''

使用标准库附带的optparse。例如:

#!/usr/bin/env python
import optparse

def main():
  p = optparse.OptionParser()
  p.add_option('--person', '-p', default="world")
  options, arguments = p.parse_args()
  print 'Hello %s' % options.person

if __name__ == '__main__':
  main()

来源:使用Python创建UNIX命令行工具

然而,从Python 2.7开始,optparse已弃用,请参阅:为什么使用argparse而不是optparse?

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)