在Python中,我们如何找到为脚本提供的命令行参数,并处理它们?


有关更具体的示例,请参见实现“[命令][动作][参数]”风格的命令行界面?以及如何使用Python的optparse格式化位置参数帮助?


当前回答

我建议使用docopt作为其他选项的简单替代。

Docopt是一个新的项目,它通过解析您的——help使用消息来工作,而不是要求您自己实现所有内容。您只需将您的使用消息放入POSIX格式。

其他回答

我的解是入口点2。例子:

from entrypoint2 import entrypoint
@entrypoint
def add(file, quiet=True): 
    ''' This function writes report.

    :param file: write report to FILE
    :param quiet: don't print status messages to stdout
    '''
    print file,quiet

帮助文本:

usage: report.py [-h] [-q] [--debug] file

This function writes report.

positional arguments:
  file         write report to FILE

optional arguments:
  -h, --help   show this help message and exit
  -q, --quiet  don't print status messages to stdout
  --debug      set logging level to DEBUG

我自己也使用optparse,但是非常喜欢Simon Willison最近引入的optfunc库。它的工作原理是:

“自省一个函数 定义(包括其参数) 以及它们的默认值)和使用 构造一个命令行 参数解析器。”

例如,这个函数定义:

def geocode(s, api_key='', geocoder='google', list_geocoders=False):

被转换为以下optparse帮助文本:

    Options:
      -h, --help            show this help message and exit
      -l, --list-geocoders
      -a API_KEY, --api-key=API_KEY
      -g GEOCODER, --geocoder=GEOCODER

新答案的原因:

现有的答案指定了多个选项。 标准选项是使用argparse,一些答案从文档中提供了示例,其中一个答案提出了它的优点。但是所有OP都不能充分/清楚地解释实际问题的答案,至少对新手来说是这样。

argparse的一个例子:

import argparse


def load_config(conf_file):
    pass


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    //Specifies one argument from the command line
    //You can have any number of arguments like this
    parser.add_argument("conf_file", help="configuration file for the application") 
    args = parser.parse_args()
    config = load_config(args.conf_file)

上面的程序需要一个配置文件作为参数。如果您提供了它,它将愉快地执行。如果没有,它将打印以下内容

usage: test.py [-h] conf_file
test.py: error: the following arguments are required: conf_file

可以指定参数是否为可选参数。 可以使用type key为参数指定预期的类型 解析器。Add_argument("年龄",type=int, help="人的年龄") 可以通过指定default key来指定参数的默认值

本文档将在一定程度上帮助您理解它。

import sys

# Command line arguments are stored into sys.argv
# print(sys.argv[1:])

# I used the slice [1:] to print all the elements except the first
# This because the first element of sys.argv is the program name
# So the first argument is sys.argv[1], the second is sys.argv[2] ecc

print("File name: " + sys.argv[0])
print("Arguments:")
for i in sys.argv[1:]:
    print(i)

让我们把这个文件命名为command_line.py,然后运行它:

C:\Users\simone> python command_line.py arg1 arg2 arg3 ecc
File name: command_line.py
Arguments:
arg1
arg2
arg3
ecc

现在让我们写一个简单的程序sum.py:

import sys

try:
    print(sum(map(float, sys.argv[1:])))
except:
    print("An error has occurred")

结果:

C:\Users\simone> python sum.py 10 4 6 3
23

我建议使用docopt作为其他选项的简单替代。

Docopt是一个新的项目,它通过解析您的——help使用消息来工作,而不是要求您自己实现所有内容。您只需将您的使用消息放入POSIX格式。