在Python中,我们如何找到为脚本提供的命令行参数,并处理它们?
有关更具体的示例,请参见实现“[命令][动作][参数]”风格的命令行界面?以及如何使用Python的optparse格式化位置参数帮助?
在Python中,我们如何找到为脚本提供的命令行参数,并处理它们?
有关更具体的示例,请参见实现“[命令][动作][参数]”风格的命令行界面?以及如何使用Python的optparse格式化位置参数帮助?
当前回答
还有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
其他回答
只是四处宣传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 正确的参数检查
如果你需要快速而不灵活的东西
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
产生以下输出:
你好,詹姆斯·史密斯
docopt库非常漂亮。它为你的应用程序从usage字符串中构建一个参数dict。
来自docopt自述文件:
"""Naval Fate.
Usage:
naval_fate.py ship new <name>...
naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
naval_fate.py ship shoot <x> <y>
naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
naval_fate.py (-h | --help)
naval_fate.py --version
Options:
-h --help Show this screen.
--version Show version.
--speed=<kn> Speed in knots [default: 10].
--moored Moored (anchored) mine.
--drifting Drifting mine.
"""
from docopt import docopt
if __name__ == '__main__':
arguments = docopt(__doc__, version='Naval Fate 2.0')
print(arguments)
新答案的原因:
现有的答案指定了多个选项。 标准选项是使用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
print("\n".join(sys.argv))
sys。Argv是一个列表,它包含在命令行上传递给脚本的所有参数。sys。Argv[0]为脚本名称。
基本上,
import sys
print(sys.argv[1:])