本文翻译自:Python argparse command line flags without arguments
How do I add an optional flag to my command line args? 如何在命令行参数中添加可选标志?
eg. 例如。 so I can write 所以我可以写
python myprog.py
or 要么
python myprog.py -w
I tried 我试过了
parser.add_argument('-w')
But I just get an error message saying 但是我收到一条错误消息说
Usage [-w W]
error: argument -w: expected one argument
which I take it means that it wants an argument value for the -w option. 我认为这意味着它需要-w选项的参数值。 What's the way of just accepting a flag? 接受旗帜的方式是什么?
I'm finding http://docs.python.org/library/argparse.html rather opaque on this question. 我在这个问题上发现http://docs.python.org/library/argparse.html相当不透明。
#1楼
参考:https://stackoom.com/question/YeXh/不带参数的Python-argparse命令行标志
#2楼
Adding a quick snippet to have it ready to execute: 添加一个快速片段以使其可以执行:
Source: myparser.py 资料来源: myparser.py
import argparse
parser = argparse.ArgumentParser(description="Flip a switch by setting a flag")
parser.add_argument('-w', action='store_true')
args = parser.parse_args()
print args.w
Usage: 用法:
python myparser.py -w
>> True
#3楼
Here's a quick way to do it, won't require anything besides sys
.. though functionality is limited: 这是一种快速的方法,尽管功能有限,但除了sys
..之外不需要任何其他东西:
flag = "--flag" in sys.argv[1:]
[1:]
is in case if the full file name is --flag
[1:]
如果完整文件名是--flag
#4楼
As you have it, the argument w is expecting a value after -w on the command line. 如您所愿,参数w在命令行中的-w之后需要一个值。 If you are just looking to flip a switch by setting a variable True
or False
, have a look at http://docs.python.org/dev/library/argparse.html#action (specifically store_true and store_false) 如果您只是想通过设置变量True
或False
来翻转开关,请查看http://docs.python.org/dev/library/argparse.html#action (特别是store_true和store_false)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-w', action='store_true')
where action='store_true'
implies default=False
. 其中action='store_true'
表示default=False
。
Conversely, you could have action='store_false'
, which implies default=True
. 相反,您可以使用action='store_false'
,这意味着default=True
。