在Python中,我们如何找到为脚本提供的命令行参数,并处理它们?
有关更具体的示例,请参见实现“[命令][动作][参数]”风格的命令行界面?以及如何使用Python的optparse格式化位置参数帮助?
在Python中,我们如何找到为脚本提供的命令行参数,并处理它们?
有关更具体的示例,请参见实现“[命令][动作][参数]”风格的命令行界面?以及如何使用Python的optparse格式化位置参数帮助?
当前回答
我喜欢从stdlib中获取getopt,例如:
try:
opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
except getopt.GetoptError, err:
usage(err)
for opt, arg in opts:
if opt in ('-h', '--help'):
usage()
if len(args) != 1:
usage("specify thing...")
最近,我一直在包装类似的东西,使事情更少的啰嗦(例如;使“-h”隐式)。
其他回答
新答案的原因:
现有的答案指定了多个选项。 标准选项是使用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来指定参数的默认值
本文档将在一定程度上帮助您理解它。
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)
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格式。
import sys
print("\n".join(sys.argv))
sys。Argv是一个列表,它包含在命令行上传递给脚本的所有参数。sys。Argv[0]为脚本名称。
基本上,
import sys
print(sys.argv[1:])