argparse python模块的文档虽然非常棒,但对于我这个初学者来说,现在还难以理解。我不需要在命令行上做数学运算,也不需要在屏幕上修改格式行或更改选项字符。我想做的就是“如果arg是A,做这个,如果B做那个,如果以上都没有显示帮助并退出”。
当前回答
代码文件:argparseDemo.py
简单:普通情况
name(abbr, full), with help 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) call python argparseDemo.py -n Crifan python argparseDemo.py --name Crifan output: args=Namespace(name='Crifan') and args.name=Crifan type argParser.add_argument("-a", "--age", type=int, help="your current age") print("type(args.age)=%s" % type(args.age)) call: python argparseDemo.py --age 30 output: type(args.age)=<class 'int'> and args.age=30 required argParser.add_argument("-a", "--age", required=True, type=int, help="your current age") call: python argparseDemo.py output: error argparseDemo.py: error: the following arguments are required: -a/--age default argParser.add_argument("-a", "--age", type=int, default=20, help="your current age. Default is 20") call: python argparseDemo.py output: args.age=20 choices argParser.add_argument("-f", "--love-fruit", choices=['apple', 'orange', 'banana'], help="your love fruits") call: python argparseDemo.py -f apple output: args=Namespace(love_fruit='apple') and args.love_fruit=apple multi args argParser.add_argument("-f", "--love-fruit", nargs=2, help="your love fruits") call: python argparseDemo.py -f apple orange output: args.love_fruit=['apple', 'orange']
细节
最简单的:-x
code: 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) usage = run in command line python argparseDemo.py -a 30 or: ./argparseDemo.py -a 30 makesure argparseDemo.py is executable if not, add it: chmod +x argparseDemo.py output args.a=30 Note default type is 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 type is Namespace print("type(args)=%s" % type(args)) -> type(args)=<class 'argparse.Namespace'> args value is Namespace(a='30') print("args=%s" % args) -> args=Namespace(a='30') so we can call/use args.a
参数名称
全参数名称:——xxx
代码 argparse。add_argument(“——”,“时代”) 使用 python argparseDemo.py -a 30 或者:python argparseDemo.py——30岁 获取解析值:args.age 注意:不是参数。a,并且不存在参数
包含多个单词的完整参数名称:——xxx-yyy
代码 argparse。add_argument(“——”“——现在的年龄”) 获取解析值:args.current_age
添加帮助说明:help
代码 argparse。Add_argument ("-a", help="your age") # with help 输出 使用——帮助可以看到描述 python argparseDemo.py——help 使用:argparseDemo.py [-h] [-a A] 可选参数: -h,——help显示帮助信息并退出 A A你的年龄
指定参数类型:type
代码 argParser。add_论证(“a”,类型=int) 输出 打印型”(args。a)“%型(args = % s。a型)- > (args。a) = < int’级> 打印(“args=%s”)-> args=Namespace(a=30)
添加默认值:default
代码 argparse。Add_argument ("-a", type=int, default=20) #如果没有传递a,则使用默认值:20 效果 用法:python argparseDemo.py 输出:打印(arg游戏。age=%s" % args.age) -> args=命名空间(a=20)
其他回答
注意Python HOWTOs中的Argparse教程。它从最基本的例子开始,比如这个:
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)
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
我浏览了所有的例子和答案,但在某种程度上,它们并没有满足我的需求。所以我会给她列出一个我需要更多帮助的场景,我希望这能更好地解释这个想法。
最初的问题
我需要开发一个工具,它得到一个文件来处理它,它需要一些可选的配置文件来配置工具。
所以我需要的是以下内容
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')
这是一个新手,但是将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"