5

I want to achive next behaviour:

python script.py 
> my_arg is None

python script.py --my-arg
> my_arg is "default"

python script.py --my-arg some_value
> my_arg is "some_value"

How to configure this argument for Argparser?

What I've tried so far:

#!/usr/bin/env python
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--my-argument', nargs='?', default='default')
args = parser.parse_args()

print(args.my_argument)

But for test.py I've got default

dkiselev
  • 890
  • 8
  • 20
  • Possible duplicate of [Python argparse: default value or specified value](https://stackoverflow.com/questions/15301147/python-argparse-default-value-or-specified-value) – Mayra Delgado Nov 05 '18 at 15:00

2 Answers2

4

Found solution here Python argparse: default value or specified value

My script looks like:

#!/usr/bin/env python
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--my-argument', nargs='?', const='default')
args = parser.parse_args()

print(args.my_argument)
Community
  • 1
  • 1
dkiselev
  • 890
  • 8
  • 20
1

How about this? Using append action to distinguish non-specified case / --my-arg specified case:

>>> import argparse
>>> 
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--my-arg', action='append', nargs='?', default=[])
>>> def parse(argv):
...     args = parser.parse_args(argv)
...     if not args.my_arg:
...         return None
...     return args.my_arg[0] or 'default'
... 
>>> parse([])  # python script.py
>>> parse(['--my-arg'])  # python script.py --my-arg
'default'
>>> parse(['--my-arg', 'some_value'])  # python script.py --my-arg some_value
'some_value'
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Very interesting solution for more complex cases, and it works, but I've found the easiest solution for my rather simple case. – dkiselev Apr 21 '16 at 10:11