没有参数的Python argparse命令行标志 [英] Python argparse command line flags without arguments

查看:31
本文介绍了没有参数的Python argparse命令行标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何向命令行参数添加可选标志?

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?

我发现 http://docs.python.org/library/argparse.html 相当不透明关于这个问题.

I'm finding http://docs.python.org/library/argparse.html rather opaque on this question.

推荐答案

正如你所拥有的,参数 w 期望在命令行上的 -w 之后有一个值.如果您只是想通过设置变量 TrueFalse 来翻转开关,请查看 这里(特别是 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 here (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命令行标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆