带有和不带价值的期权被接受

Pet*_*tal 3 python argparse

我有一个小脚本,我需要它能够接受带有值和没有值的参数。

./cha.py --pretty-xml
./cha.py --pretty-xml=5
Run Code Online (Sandbox Code Playgroud)

我有这个。

parser.add_argument('--pretty-xml', nargs='?', dest='xml_space', default=4)
Run Code Online (Sandbox Code Playgroud)

但是,当我在xml_space中使用--pretty-xml时将为“ none”。如果我不写此参数,则在xml_space中存储默认值。我需要完全相反。

小智 5

使用const关键字:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--pretty-xml", nargs="?", type=int, dest="xml_space", const=4)
print(parser.parse_args([]))
print(parser.parse_args(['--pretty-xml']))
print(parser.parse_args(['--pretty-xml=5']))
Run Code Online (Sandbox Code Playgroud)

结果是

Namespace(xml_space=None)
Namespace(xml_space=4)
Namespace(xml_space=5)
Run Code Online (Sandbox Code Playgroud)