不带参数的Python argparse命令行标志

编程入门 行业动态 更新时间:2024-10-23 03:33:01
本文介绍了不带参数的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?

我发现 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命令行标志

本文发布于:2023-10-04 07:46:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1467134.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不带   命令行   标志   参数   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!