argparse python模块的文档虽然非常棒,但对于我这个初学者来说,现在还难以理解。我不需要在命令行上做数学运算,也不需要在屏幕上修改格式行或更改选项字符。我想做的就是“如果arg是A,做这个,如果B做那个,如果以上都没有显示帮助并退出”。
当前回答
下面是我使用argparse(使用多个args)的方法:
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
在您的情况下,只需添加一个参数。
其他回答
由于你没有澄清参数“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
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')
上面的代码将分别创建值为True的变量'foo'和值为False的变量'no_foo':
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,参数名作为键,值作为值。
还有许多其他选项和可以做的事情,但这应该涵盖最基本的常见使用场景。
补充一下其他人已经说过的话:
我通常喜欢使用'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!"
代码文件: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)
使用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