Python argparse默认值不生效问题排查求助
为什么argparse的默认值在我的程序里不生效?
嘿,我一眼就发现问题所在了——你给x、y和operation定义的是位置参数,而argparse里的位置参数默认是必填项,哪怕你设置了default参数也不会生效!
问题根源
位置参数是那种不需要任何前缀(比如--),直接在命令行按顺序输入的参数。argparse会默认认为用户必须提供这些参数的值,所以当你不带任何参数运行程序时,就会抛出你看到的“缺少必填参数”错误。
两种解决方案
方案1:改成可选参数(推荐)
给参数加上--前缀,把它们变成可选参数。这样用户可以选择是否指定参数值,不指定时就会自动使用你设置的默认值。修改后的代码如下:
'''This simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument.''' import argparse import sys def calc(args): operation = args.operation x = args.x y = args.y if operation == "add": return x + y elif operation == "sub": return x - y parser = argparse.ArgumentParser(description="This is a summing program") # 给参数添加--前缀,转为可选参数 parser.add_argument("--x", type=float, default=1.0, help="What is the first number?") parser.add_argument("--y", type=float, default=1.0, help='What is the second number?') parser.add_argument("--operation", type=str, default="add", help='What operation? Can choose add, sub, mul, or div') args = parser.parse_args() print(str(calc(args)))
现在运行python cmdline.py就会直接使用默认值计算;如果需要自定义参数,就用类似python cmdline.py --x 5 --y 3 --operation sub的方式调用。
方案2:保留位置参数但设为可选
如果你想继续用位置参数的形式,只需要给每个参数加上nargs='?',表示这个位置参数是可选的,用户不提供时就会用default的值:
'''This simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument.''' import argparse import sys def calc(args): operation = args.operation x = args.x y = args.y if operation == "add": return x + y elif operation == "sub": return x - y parser = argparse.ArgumentParser(description="This is a summing program") # 添加nargs='?'让位置参数变为可选 parser.add_argument("x", type=float, default=1.0, nargs='?', help="What is the first number?") parser.add_argument("y", type=float, default=1.0, nargs='?', help='What is the second number?') parser.add_argument("operation", type=str, default="add", nargs='?', help='What operation? Can choose add, sub, mul, or div') args = parser.parse_args() print(str(calc(args)))
这种方式下,你可以灵活调用:
python cmdline.py:使用所有默认值python cmdline.py 2 3:指定x=2、y=3,operation用默认的addpython cmdline.py 4 5 sub:指定所有三个参数
总结
两种方案各有优劣:可选参数更清晰,适合参数较多或需要明确指定的场景;位置参数更简洁,适合常用的、顺序固定的参数。你可以根据自己的需求选择~
内容的提问来源于stack exchange,提问作者Legion
相关产品推荐
相关产品推荐

