Python 如何使用argparse解析开/关(调试)标志?

Python 如何使用argparse解析开/关(调试)标志?,python,argparse,Python,Argparse,我的CLI程序使用--debug标志来决定是否打印调试消息。当指定了--debug时,应打印调试消息;否则,它不应打印调试消息 我目前的做法是: parser.add_参数('--debug',help='将调试消息打印到stderr',nargs='?') 但是,--help消息表明此方法无法实现我的目标: optional arguments: -h, --help show this help message and exit --debug [DEBUG] prin

我的CLI程序使用
--debug
标志来决定是否打印调试消息。当指定了
--debug
时,应打印调试消息;否则,它不应打印调试消息

我目前的做法是:

parser.add_参数('--debug',help='将调试消息打印到stderr',nargs='?')

但是,
--help
消息表明此方法无法实现我的目标:

optional arguments:
  -h, --help       show this help message and exit
  --debug [DEBUG]  print debug messages to stderr
正如您所看到的,它希望在标志后面有一个值;但是,
--debug
是一个开/关参数


我应该怎么做?

使用
存储\u true
操作:

parser.add_argument(
    '--debug',
    action='store_true', 
    help='print debug messages to stderr'
)
nargs='?'
只应用于具有一个或多个参数(回退到默认值)的选项