Python argparse:“无法识别的参数”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31469847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python argparse: "unrecognized arguments"
提问by Zvonimir Peran
I am trying to use my program with command line option. Here is my code:
我正在尝试将我的程序与命令行选项一起使用。这是我的代码:
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-u","--upgrade", help="fully automatized upgrade")
args = parser.parse_args()
if args.upgrade:
print "Starting with upgrade procedure"
main()
When I try to run my program from terminal (python script.py -u
), I expect to get the message Starting with upgrade procedure
, but instead I get the error message unrecognized arguments -u
.
当我尝试从终端 ( python script.py -u
)运行我的程序时,我希望收到消息Starting with upgrade procedure
,但我收到的是错误消息unrecognized arguments -u
。
采纳答案by Rakholiya Jenish
The error you are getting is because -u
is expecting a some value after it. If you use python script.py -h
you will find it in usage statement saying [-u UPGRADE]
.
您得到的错误是因为-u
期望在它之后有一些价值。如果您使用,python script.py -h
您会在使用声明中找到它[-u UPGRADE]
。
If you want to use it as boolean or flag (true if -u
is used), add an additional parameter action
:
如果要将其用作布尔值或标志(如果-u
使用则为 true ),请添加一个附加参数action
:
parser.add_argument("-u","--upgrade", help="fully automatized upgrade", action="store_true")
action
- The basic type of action to be taken when this argument is encountered at the command line
action
- 在命令行遇到此参数时要采取的基本操作类型
With action="store_true"
, if the option -u
is specified, the value True is assigned to args.upgrade
. Not specifying it implies False.
对于action="store_true"
,如果-u
指定了该选项,则将值 True 分配给args.upgrade
。不指定它意味着 False。
Source: Python argparse documentation
回答by Anand S Kumar
Currently, your argument requires a value to be passed in for it as well.
目前,您的参数还需要为其传入一个值。
If you want -u
as an option instead, Use the action='store_true'
for arguments that do not need a value.
如果您想要-u
作为选项,请使用action='store_true'
for 不需要值的参数。
Example -
例子 -
parser.add_argument("-u","--upgrade", help="fully automatized upgrade", action='store_true')
回答by Nitesh Patel
For Boolean arguments use action="store_true":
对于布尔参数,使用 action="store_true":
parser.add_argument("-u","--upgrade", help="fully automatized upgrade", action="store_true")
See: https://docs.python.org/2/howto/argparse.html#introducing-optional-arguments
请参阅:https: //docs.python.org/2/howto/argparse.html#introducing-optional-arguments