Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Option accepted with and without value

I have a small script and I need it to be able to accept parameter with value and withou value.

./cha.py --pretty-xml
./cha.py --pretty-xml=5

I have this.

parser.add_argument('--pretty-xml', nargs='?', dest='xml_space', default=4)

But when I use --pretty-xml in xml_space will be 'none'. If I dont write this parameter in xml_space is stored the default value. I would need the exact opposite.

like image 340
Petr Nechvátal Avatar asked Oct 27 '25 04:10

Petr Nechvátal


1 Answers

Use the const keyword:

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']))

results in

Namespace(xml_space=None)
Namespace(xml_space=4)
Namespace(xml_space=5)

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!