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

查看:110
本文介绍了不带参数的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来翻转开关,请查看 http://docs.python.org/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 http://docs.python.org/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命令行标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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