如何在命令行参数中添加可选标志?
How do I add an optional flag to my command line args?
例如所以我可以写
python myprog.py或
python myprog.py -w我尝试了
parser.add_argument('-w')但是我只收到一条错误消息,说
But I just get an error message saying
Usage [-w W] error: argument -w: expected one argument我认为这意味着它需要-w选项的参数值.接受标志的方式是什么?
which I take it means that it wants an argument value for the -w option. What's the way of just accepting a flag?
我发现 docs.python/library/argparse.html 相当不透明关于这个问题.
I'm finding docs.python/library/argparse.html rather opaque on this question.
推荐答案如您所知,参数w在命令行中的-w之后期望值.如果您只是想通过设置变量True或False来翻转开关,请查看 docs.python/dev/library/argparse.html#action (特别是store_true和store_false)
As you have it, the argument w is expecting a value after -w on the command line. If you are just looking to flip a switch by setting a variable True or False, have a look at docs.python/dev/library/argparse.html#action (specifically store_true and store_false)
import argparse parser = argparse.ArgumentParser() parser.add_argument('-w', action='store_true')其中action='store_true'表示default=False.
相反,您可以拥有action='store_false',这意味着default=True.
Conversely, you could haveaction='store_false', which implies default=True.
更多推荐
不带参数的Python argparse命令行标志
发布评论