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)
其他回答
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
这是另一个总结介绍,受这篇文章的启发。
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: description for this arg when --help is used. default: default value if the arg is omitted. type: if you expect a float or int (otherwise is str). dest: give a different name to a flag (e.g. '-x', '--long-name', dest='longName'). Note: by default --long-name is accessed with args.long_name action: for special handling of certain arguments store_true, store_false: for boolean args '--foo', action='store_true' => args.foo == True store_const: to be used with option const '--foo', action='store_const', const=42 => args.foo == 42 count: for repeated options, as in ./myscript.py -vv '-v', action='count' => args.v == 2 append: for repeated options, as in ./myscript.py --foo 1 --foo 2 '--foo', action='append' => args.foo == ['1', '2'] required: if a flag is required, or a positional argument is not. nargs: for a flag to capture N args ./myscript.py --foo a b => args.foo = ['a', 'b'] choices: to restrict possible inputs (specify as list of strings, or ints if type=int).
注意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)
使用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
作为现有答案的补充,如果你足够懒惰,可以使用称为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:正如规则中提到的,我必须指定这是我自己的项目
推荐文章
- 如何在交互式Python中查看整个命令历史?
- 如何显示有两个小数点后的浮点数?
- 如何用OpenCV2.0和Python2.6调整图像大小
- 在每个列表元素上调用int()函数?
- 当使用代码存储库时,如何引用资源的相对路径
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置
- Python Pandas只合并某些列
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?