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


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


当前回答

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

其他回答

只是四处宣传argparse,因为这些原因它更好。从本质上讲:

(从链接复制)

argparse module can handle positional and optional arguments, while optparse can handle only optional arguments argparse isn’t dogmatic about what your command line interface should look like - options like -file or /file are supported, as are required options. Optparse refuses to support these features, preferring purity over practicality argparse produces more informative usage messages, including command-line usage determined from your arguments, and help messages for both positional and optional arguments. The optparse module requires you to write your own usage string, and has no way to display help for positional arguments. argparse supports action that consume a variable number of command-line args, while optparse requires that the exact number of arguments (e.g. 1, 2, or 3) be known in advance argparse supports parsers that dispatch to sub-commands, while optparse requires setting allow_interspersed_args and doing the parser dispatch manually

我个人最喜欢的是:

Argparse允许类型和 add_argument()的操作参数 用simple指定 调用对象,而optparse需要 破解类属性,比如 获取STORE_ACTIONS或CHECK_METHODS 正确的参数检查

还有argparse stdlib模块(对stdlib的optparse模块的“改进”)。示例来自argparse的介绍:

# script.py
import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'integers', metavar='int', type=int, choices=range(10),
         nargs='+', help='an integer in the range 0..9')
    parser.add_argument(
        '--sum', dest='accumulate', action='store_const', const=sum,
        default=max, help='sum the integers (default: find the max)')

    args = parser.parse_args()
    print(args.accumulate(args.integers))

用法:

$ script.py 1 2 3 4
4

$ script.py --sum 1 2 3 4
10

Pocoo的点击更直观,需要的样板文件更少,而且至少和argparse一样强大。

到目前为止,我遇到的唯一缺点是您不能对帮助页面进行很多自定义,但这通常不是必需的,而docopt似乎是明确的选择。

我自己也使用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

如果你需要快速而不灵活的东西

main.py:

import sys

first_name = sys.argv[1]
last_name = sys.argv[2]
print("Hello " + first_name + " " + last_name)

然后运行python main.py James Smith

产生以下输出:

你好,詹姆斯·史密斯