argparse python模块的文档虽然非常棒,但对于我这个初学者来说,现在还难以理解。我不需要在命令行上做数学运算,也不需要在屏幕上修改格式行或更改选项字符。我想做的就是“如果arg是A,做这个,如果B做那个,如果以上都没有显示帮助并退出”。
当前回答
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位置参数的值。第一个显然是错误的(它是一个算术表达式。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
其他回答
以下是我在学习项目中想到的,主要感谢@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
这是一个新手,但是将Python与Powershell结合起来并使用这个模板,灵感来自深入而伟大的Python命令行参数-真正的Python
在init_argparse()中可以做很多事情,这里我只介绍最简单的场景。
import argparse use if __name__ == "__main__": main() pattern to execute from terminal parse arguments within the main() function that has no parameters as all define a init_argparse() function create a parser object by calling argparse.ArgumentParser() declare one or more argumnent with parser.add_argument("--<long_param_name>") return parser parse args by creating an args object by calling parser.parse_args() define a function proper with param1, param2, ... call function_proper with params being assigned as attributes of an args object e.g. function_proper(param1=args.param1, param2=args.param2) within a shell call the module with named arguments: e.g. 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"
作为现有答案的补充,如果你足够懒惰,可以使用称为protoargs的代码生成工具。它从配置生成参数解析器。对于python,它使用argparse。
配置可选A和B:
syntax = "proto2";
message protoargs
{
optional string A = 1; // A param description
optional string B = 2; // B param description
}//protoargs
配置所需的A和B:
syntax = "proto2";
message protoargs
{
required string A = 1; // A param description
required string B = 2; // B param description
}//protoargs
位置A和B的构型:
syntax = "proto2";
message protoargs
{
required string A = 1; // A param description
required string B = 2; // B param description
}//protoargs
message protoargs_links
{
}//protoargs_links
现在你要做的就是:
python ./protoargs.py -i test.proto -o . --py
并使用它(这里可以举其他例子):
import sys
import test_pa
class ArgsParser:
program = "test"
description = "Simple A and B parser test."
def parse(self, argv):
self.config = test_pa.parse(self.program, self.description, argv)
def usage(self):
return test_pa.usage(self.program, self.description)
if __name__ == "__main__":
parser = ArgsParser()
if len(sys.argv) == 1:
print(parser.usage())
else:
parser.parse(sys.argv[1:])
if parser.config.A:
print(parser.config.A)
if parser.config.B:
print(parser.config.B)
如果你想要更多的改变配置,重新生成解析器,使用更新的parser.config。
UPD:正如规则中提到的,我必须指定这是我自己的项目
也可以使用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
usage: example.py [-h] {A,B}
example.py: error: argument arg: invalid choice: 'C' (choose from 'A', 'B')
提供正确的参数- example.py
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参数后的元组注释的含义如下:
描述(有两个可能值的参数) 参数类型- 'flag', 'option'或'positional' (positional)之一 缩写(无) 参数值的类型-例如。float, string (None) 限制选项集(['A', 'B'])
文档:
要了解更多关于使用placa的知识,请查看它的伟大文档:
Plac:解析命令行的简单方法
由于你没有澄清参数“A”和“B”是位置的还是可选的,我将两者混合。
默认情况下,位置参数是必需的。如果没有给出一个将抛出'Few arguments given'这不是可选参数的情况下,以他们的名字。默认情况下,此程序将接受一个数字并返回其方框,如果使用cube选项,则将返回其方框。
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
这里的可选参数是有值的,如果你只是想把它当作一个标志来使用,你也可以。因此,通过对square使用-s,对cube使用-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
推荐文章
- 在python中,年龄从出生日期开始
- 使用pip安装SciPy
- 在Python中,我应该如何测试变量是否为None, True或False
- 如何在Python中从毫秒创建datetime ?
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀
- 为什么空字典在Python中是一个危险的默认值?
- 在Python中,冒号等于(:=)是什么意思?
- Python "SyntaxError:文件中的非ascii字符'\xe2' "
- 如何从psycopg2游标获得列名列表?
- Python中dict对象的联合
- 如何有效地比较两个无序列表(不是集合)?