documentation的argparse python module虽然非常好,但我确信,这对于我的初学者大脑来说太过分了。我不需要在命令行上进行数学运算,也不需要在屏幕上使用格式化线条或更改选项字符。我想做的只是“如果arg是A,那么,如果B这样做,如果上述任何一个都不显示帮助并退出”。
答案 0 :(得分:333)
这是我用argparse
(有多个参数)的方式:
parser = argparse.ArgumentParser(description='Description of your program')
parser.add_argument('-f','--foo', help='Description for foo argument', required=True)
parser.add_argument('-b','--bar', help='Description for bar argument', required=True)
args = vars(parser.parse_args())
args
将是一个包含参数的字典:
if args['foo'] == 'Hello':
# code here
if args['bar'] == 'World':
# code here
在您的情况下,只需添加一个参数。
答案 1 :(得分:224)
我对原始问题的理解是双重的。首先,就最简单的argparse示例而言,我很惊讶我在这里没有看到它。当然,为了简单起见,它也是一点点动力,但它可能会让你开始。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("a")
args = parser.parse_args()
if args.a == 'magic.name':
print 'You nailed it!'
但现在需要这个位置论证。如果在调用此程序时将其遗漏,则会收到有关缺少参数的错误。这引出了我原始问题的第二部分。 Matt Wilkie似乎想要一个没有命名标签的可选参数( - 选项标签)。我的建议是修改上面的代码如下:
...
parser.add_argument("a", nargs='?', default="check_string_for_empty")
...
if args.a == 'check_string_for_empty':
print 'I can tell that no argument was given and I can deal with that here.'
elif args.a == 'magic.name':
print 'You nailed it!'
else:
print args.a
可能有一个更优雅的解决方案,但这是有效的,并且极简主义。
答案 2 :(得分:195)
argparse
文档相当不错,但遗漏了一些可能不太明显的有用细节。 (@Diego Navarro已经提到了其中一些但我会尝试稍微扩展他的答案。)基本用法如下:
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--my-foo', default='foobar')
parser.add_argument('-b', '--bar-value', default=3.14)
args = parser.parse_args()
从parse_args()
返回的对象是一个'Namespace'对象:一个对象,其成员变量以命令行参数命名。 Namespace
对象是您访问参数及其相关值的方式:
args = parser.parse_args()
print args.my_foo
print args.bar_value
(注意argparse
在命名变量时用下划线替换你的参数名中的' - '。)
在许多情况下,您可能希望将参数简单地用作不带值的标志。你可以像这样在argparse中添加它们:
parser.add_argument('--foo', action='store_true')
parser.add_argument('--no-foo', action='store_false')
上面将分别创建名为'foo'的值为True的变量,以及'no_foo',其值为False:
if (args.foo):
print "foo is true"
if (args.no_foo is False):
print "nofoo is false"
另请注意,添加参数时可以使用“required”选项:
parser.add_argument('-o', '--output', required=True)
这样,如果在命令行argparse
中省略此参数,则会告诉您它已丢失并停止执行您的脚本。
最后,请注意,可以使用vars
函数创建参数的dict结构,如果这样可以让您的生活更轻松。
args = parser.parse_args()
argsdict = vars(args)
print argsdict['my_foo']
print argsdict['bar_value']
如您所见,vars
返回一个dict,其中您的参数名称为键,其值为er,值。
您可以执行许多其他选项和操作,但这应涵盖最重要的常见使用方案。
答案 3 :(得分:55)
Matt询问argparse中的位置参数,我同意Python文档在这方面缺乏。在大约20多个页面中没有一个完整的例子显示解析和使用位置参数。
这里没有其他答案显示位置参数的完整示例,所以这是一个完整的例子:
# tested with python 2.7.1
import argparse
parser = argparse.ArgumentParser(description="An argparse example")
parser.add_argument('action', help='The action to take (e.g. install, remove, etc.)')
parser.add_argument('foo-bar', help='Hyphens are cumbersome in positional arguments')
args = parser.parse_args()
if args.action == "install":
print("You asked for installation")
else:
print("You asked for something other than installation")
# The following do not work:
# print(args.foo-bar)
# print(args.foo_bar)
# But this works:
print(getattr(args, 'foo-bar'))
让我失望的是argparse将命名参数“--foo-bar”转换为“foo_bar”,但名为“foo-bar”的位置参数保持为“foo-bar”,使其更少很明显如何在你的程序中使用它。
注意我示例末尾附近的两行 - 这两行都不能用于获取foo-bar位置参数的值。第一个显然是错误的(它是一个算术表达式args.foo减去bar),但第二个也不起作用:
AttributeError: 'Namespace' object has no attribute 'foo_bar'
如果您想使用foo-bar
属性,则必须使用getattr
,如我示例的最后一行所示。令人抓狂的是,如果您尝试使用dest=foo_bar
将属性名称更改为更容易访问的内容,则会收到一条非常奇怪的错误消息:
ValueError: dest supplied twice for positional argument
以下是上述示例的运行方式:
$ python test.py
usage: test.py [-h] action foo-bar
test.py: error: too few arguments
$ python test.py -h
usage: test.py [-h] action foo-bar
An argparse example
positional arguments:
action The action to take (e.g. install, remove, etc.)
foo-bar Hyphens are cumbersome in positional arguments
optional arguments:
-h, --help show this help message and exit
$ python test.py install foo
You asked for installation
foo
答案 4 :(得分:13)
另一个摘要介绍,受this post启发。
import argparse
# define functions, classes, etc.
# executes when your script is called from the command-line
if __name__ == "__main__":
parser = argparse.ArgumentParser()
#
# define each option with: parser.add_argument
#
args = parser.parse_args() # automatically looks at sys.argv
#
# access results with: args.argumentName
#
使用以下各项的组合定义参数:
parser.add_argument( 'name', options... ) # positional argument
parser.add_argument( '-x', options... ) # single-char flag
parser.add_argument( '-x', '--long-name', options... ) # flag with long name
常见选项包括:
--help
时此arg的说明。float
或int
(否则为str
)。'-x', '--long-name', dest='longName'
)。注意:默认--long-name
是通过args.long_name
<访问的/ em>的store_true, store_false
:表示布尔args为'--foo', action='store_true' => args.foo == True
store_const
与选项const
一起使用<{1}} '--foo', action='store_const', const=42 => args.foo == 42
:重复选项,例如count
./myscript.py -vv
'-v', action='count' => args.v == 2
:重复选项,例如append
./myscript.py --foo 1 --foo 2
'--foo', action='append' => args.foo == ['1', '2']
./myscript.py --foo a b => args.foo = ['a', 'b']
则指定为in。)答案 5 :(得分:10)
请注意Argparse Tutorial中的Python HOWTOs。它从大多数基本示例开始,如下所示:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
args = parser.parse_args()
print(args.square**2)
并发展到不太基本的。
有一个选项的预定义选项示例,例如:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
print("the square of {} equals {}".format(args.square, answer))
elif args.verbosity == 1:
print("{}^2 == {}".format(args.square, answer))
else:
print(answer)
答案 6 :(得分:10)
这是我在学习项目中提出的,主要归功于@DMH ......
演示代码:
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--flag', action='store_true', default=False) # can 'store_false' for no-xxx flags
parser.add_argument('-r', '--reqd', required=True)
parser.add_argument('-o', '--opt', default='fallback')
parser.add_argument('arg', nargs='*') # use '+' for 1 or more args (instead of 0 or more)
parsed = parser.parse_args()
# NOTE: args with '-' have it replaced with '_'
print('Result:', vars(parsed))
print('parsed.reqd:', parsed.reqd)
if __name__ == "__main__":
main()
这可能已经发展并可在线获取:command-line.py
为此代码提供锻炼的脚本:command-line-demo.sh
答案 7 :(得分:4)
您还可以使用plac(argparse
周围的包装)。
作为奖励,它会产生简洁的帮助说明 - 见下文。
#!/usr/bin/env python3
def main(
arg: ('Argument with two possible values', 'positional', None, None, ['A', 'B'])
):
"""General help for application"""
if arg == 'A':
print("Argument has value A")
elif arg == 'B':
print("Argument has value B")
if __name__ == '__main__':
import plac
plac.call(main)
没有提供参数 - example.py
:
usage: example.py [-h] {A,B}
example.py: error: the following arguments are required: arg
提供了意外的参数 - example.py C
:
usage: example.py [-h] {A,B}
example.py: error: argument arg: invalid choice: 'C' (choose from 'A', 'B')
提供正确的参数 - example.py A
:
Argument has value A
完整帮助菜单(自动生成) - example.py -h
:
usage: example.py [-h] {A,B}
General help for application
positional arguments:
{A,B} Argument with two possible values
optional arguments:
-h, --help show this help message and exit
参数的名称通常等于参数名称(arg
)。
arg
参数后面的元组注释具有以下含义:
Argument with two possible values
)positional
)None
)None
)['A', 'B']
)要了解有关使用plac的更多信息,请查看其出色的文档:
答案 8 :(得分:3)
添加其他人所说的内容:
我通常喜欢使用'dest'参数来指定变量名,然后使用'globals()。update()'将这些变量放在全局命名空间中。
用法:
$ python script.py -i "Hello, World!"
代码:
...
parser.add_argument('-i', '--input', ..., dest='inputted_variable',...)
globals().update(vars(parser.parse_args()))
...
print(inputted_variable) # Prints "Hello, World!"
答案 9 :(得分:2)
代码文件:argparseDemo.py
import argparse
argParser = argparse.ArgumentParser()
argParser.add_argument("-n", "--name", help="your name")
args = argParser.parse_args()
print("args=%s" % args)
print("args.name=%s" % args.name)
python argparseDemo.py -n Crifan
python argparseDemo.py --name Crifan
args=Namespace(name='Crifan')
和 args.name=Crifan
argParser.add_argument("-a", "--age", type=int, help="your current age")
print("type(args.age)=%s" % type(args.age))
python argparseDemo.py --age 30
type(args.age)=<class 'int'>
和 args.age=30
argParser.add_argument("-a", "--age", required=True, type=int, help="your current age")
python argparseDemo.py
argparseDemo.py: error: the following arguments are required: -a/--age
argParser.add_argument("-a", "--age", type=int, default=20, help="your current age. Default is 20")
python argparseDemo.py
args.age=20
argParser.add_argument("-f", "--love-fruit", choices=['apple', 'orange', 'banana'], help="your love fruits")
python argparseDemo.py -f apple
args=Namespace(love_fruit='apple')
和 args.love_fruit=apple
argParser.add_argument("-f", "--love-fruit", nargs=2, help="your love fruits")
python argparseDemo.py -f apple orange
args.love_fruit=['apple', 'orange']
-x
代码:
import argparse
argParser = argparse.ArgumentParser()
argParser.add_argument("-a") # most simple -> got args.a, type is `str`
args = argParser.parse_args()
print("args.a=%s" % args.a)
用法 = 在命令行中运行
python argparseDemo.py -a 30
./argparseDemo.py -a 30
argparseDemo.py
是可执行的
chmod +x argparseDemo.py
输出
args.a=30
注意
str
argParser.add_argument("-a")
== argParser.add_argument("-a", type=str)
print("type(args.a)=%s" % type(args.a))
-> type(args.a)=<class 'str'>
args
类型为 Namespace
print("type(args)=%s" % type(args))
-> type(args)=<class 'argparse.Namespace'>
args
值为 Namespace(a='30')
print("args=%s" % args)
-> args=Namespace(a='30')
args.a
--xxx
argParser.add_argument("-a", "--age")
python argparseDemo.py -a 30
python argparseDemo.py --age 30
args.age
args.a
,并且NOT存在 args.a
--xxx-yyy
argParser.add_argument("-a", "--current-age")
help
argParser.add_argument("-a", help="your age") # with help
--help
可以看到说明
python argparseDemo.py --help
usage: argparseDemo.py [-h] [-a A]
optional arguments:
-h, --help show this help message and exit
-a A your age
type
argParser.add_argument("-a", type=int) # parsed arg is `int`, not default `str`
print("type(args.a)=%s" % type(args.a))
-> type(args.a)=<class 'int'>
print("args=%s" % args)
-> args=Namespace(a=30)
default
argParser.add_argument("-a", type=int, default=20) # if not pass a, a use default value: 20
python argparseDemo.py
print("args.age=%s" % args.age)
-> args=Namespace(a=20)
答案 10 :(得分:1)
使用argparse并修改'-h'/'--help'开关以显示自己的个人代码帮助说明的一种非常简单的方法是将默认帮助设置为False,还可以添加尽可能多的其他.add_arguments如您所愿:
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-h', '--help', action='help',
help='To run this script please provide two arguments')
parser.parse_args()
运行:python test.py -h
输出:
usage: test.py [-h]
optional arguments:
-h, --help To run this script please provide two arguments
答案 11 :(得分:1)
我浏览了所有示例和答案,但在某种程度上,它们并没有满足我的需求。因此,我将为她列出一个需要更多帮助的情况,希望这可以进一步解释这个想法。
我需要开发一个工具,该工具正在获取文件来处理它,并且需要一些可选的配置文件来配置工具。
所以我需要的是类似以下的东西
mytool.py file.text -config config-file.json
这是解决方案代码
import argparse
def main():
parser = argparse.ArgumentParser(description='This example for a tool to process a file and configure the tool using a config file.')
parser.add_argument('filename', help="Input file either text, image or video")
# parser.add_argument('config_file', help="a JSON file to load the initial configuration ")
# parser.add_argument('-c', '--config_file', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)
parser.add_argument('-c', '--config', default='configFile.json', dest='config_file', help="a JSON file to load the initial configuration " )
parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )
args = parser.parse_args()
filename = args.filename
configfile = args.config_file
print("The file to be processed is", filename)
print("The config file is", configfile)
if args.debug:
print("Debug mode enabled")
else:
print("Debug mode disabled")
print("and all arguments are: ", args)
if __name__ == '__main__':
main()
我将以多种增强方式展示该解决方案,以展示创意
将所有输入列为强制输入,以便第二个参数为
parser.add_argument('config_file', help="a JSON file to load the initial configuration ")
获得此工具的帮助命令后,我们发现以下结果
(base) > python .\argparser_example.py -h
usage: argparser_example.py [-h] filename config_file
This example for a tool to process a file and configure the tool using a config file.
positional arguments:
filename Input file either text, image or video
config_file a JSON file to load the initial configuration
optional arguments:
-h, --help show this help message and exit
以及当我按以下方式执行时
(base) > python .\argparser_example.py filename.txt configfile.json
结果将是
The file to be processed is filename.txt
The config file is configfile.json
and all arguments are: Namespace(config_file='configfile.json', filename='filename.txt')
但是配置文件应该是可选的,我从参数中将其删除
(base) > python .\argparser_example.py filename.txt
结果将是:
usage: argparser_example.py [-h] filename config_file
argparser_example.py: error: the following arguments are required: c
这意味着我们在工具中遇到了问题
为了使其成为可选,我对程序进行了如下修改
parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)
帮助结果应该是
usage: argparser_example.py [-h] [-c CONFIG] filename
This example for a tool to process a file and configure the tool using a config file.
positional arguments:
filename Input file either text, image or video
optional arguments:
-h, --help show this help message and exit
-c CONFIG, --config CONFIG
a JSON file to load the initial configuration
所以当我执行程序时
(base) > python .\argparser_example.py filename.txt
结果将是
The file to be processed is filename.txt
The config file is configFile.json
and all arguments are: Namespace(config_file='configFile.json', filename='filename.txt')
带有类似
的参数(base) > python .\argparser_example.py filename.txt --config_file anotherConfig.json
结果将是
The file to be processed is filename.txt
The config file is anotherConfig.json
and all arguments are: Namespace(config_file='anotherConfig.json', filename='filename.txt')
将标记名从--config_file
更改为--config
,同时保持变量名不变,我们将代码修改为包含dest='config_file'
如下:
parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', dest='config_file')
命令将是
(base) > python .\argparser_example.py filename.txt --config anotherConfig.json
要添加对具有调试模式标志的支持,我们需要在参数中添加一个标志以支持布尔调试标志。为了实现它,我添加了以下内容:
parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )
该工具命令将为:
(carnd-term1-38) > python .\argparser_example.py image.jpg -c imageConfig,json --debug
结果将是
The file to be processed is image.jpg
The config file is imageConfig,json
Debug mode enabled
and all arguments are: Namespace(config_file='imageConfig,json', debug=True, filename='image.jpg')
答案 12 :(得分:0)
由于您还没有弄清楚参数“ A”和“ B”是位置参数还是可选参数,因此我将两者混为一谈。
默认情况下需要位置参数。如果不给出,则将抛出“给出的参数很少”,而可选参数的名称则不是这种情况。该程序将使用一个数字并默认返回其平方,如果使用了多维数据集选项,则它将返回其立方。
import argparse
parser = argparse.ArgumentParser('number-game')
parser.add_argument(
"number",
type=int,
help="enter a number"
)
parser.add_argument(
"-c", "--choice",
choices=['square','cube'],
help="choose what you need to do with the number"
)
# all the results will be parsed by the parser and stored in args
args = parser.parse_args()
# if square is selected return the square, same for cube
if args.c == 'square':
print("{} is the result".format(args.number**2))
elif args.c == 'cube':
print("{} is the result".format(args.number**3))
else:
print("{} is not changed".format(args.number))
用法
$python3 script.py 4 -c square
16
在这里,可选参数正在取值,如果您只是想像标记一样使用它,也可以。因此,通过使用-s表示正方形,使用-c表示立方体,我们通过添加action =“ store_true”来更改行为。仅在使用时更改为true。
parser.add_argument(
"-s", "--square",
help="returns the square of number",
action="store_true"
)
parser.add_argument(
"-c", "--cube",
help="returns the cube of number",
action="store_true"
)
因此条件块可以更改为
if args.s:
print("{} is the result".format(args.number**2))
elif args.c:
print("{} is the result".format(args.number**3))
else:
print("{} is not changed".format(args.number))
用法
$python3 script.py 4 -c
64
答案 13 :(得分:0)
此方面的新手,但结合 Python 与 Powershell 并使用此模板,灵感来自深入而出色的 Python Command Line Arguments – Real Python
您可以在 init_argparse()
中做很多事情,我在这里只介绍最简单的场景。
import argparse
if __name__ == "__main__": main()
模式从终端执行main()
函数中没有参数的所有参数init_argparse()
函数
argparse.ArgumentParser()
创建解析器对象parser.add_argument("--<long_param_name>")
声明一个或多个参数args
来创建 parser.parse_args()
对象来解析参数param1
, param2
, ... 定义一个合适的函数function_proper
并将参数分配为 args
对象的属性
python foobar.py --param1="foo" --param2=="bar"
#file: foobar.py
import argparse
def function_proper(param1, param2):
#CODE...
def init_argparse() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser()
parser.add_argument("--param1")
parser.add_argument("--param2")
return parser
def main() -> None:
parser = init_argparse()
args = parser.parse_args()
function_proper(param1=args.param1, param2=args.param2)
if __name__ == "__main__":
main()
>>> python .\foobar.py --param1="foo" --param2=="bar"
答案 14 :(得分:-1)
最简单的答案!
P.S。撰写argparse文件的人是愚蠢的
python代码:
import argparse
parser = argparse.ArgumentParser(description='')
parser.add_argument('--o_dct_fname',type=str)
parser.add_argument('--tp',type=str)
parser.add_argument('--new_res_set',type=int)
args = parser.parse_args()
o_dct_fname = args.o_dct_fname
tp = args.tp
new_res_set = args.new_res_set
运行代码
python produce_result.py --o_dct_fname o_dct --tp father_child --new_res_set 1