1

So I am trying to implement argparse in my Python code.
I want to have lets say 4 possible arguments that could be passed. But, if I choose the fourth then I would need an additional argument, but I can't implement this.

parser = argparse.ArgumentParser(description='Testing arguments')
parser.add_argument("--a", action="store_true")
parser.add_argument("--b", action="store_true")
parser.add_argument("--c", action="store_true")
parser.add_argument("--d", action="store_true")
args = parser.parse_args()

Example:

python3 mycode.py --a #no further argument needed  
python3 mycode.py --d further_argument # further argument needed

I have read some of the posts on Stackoverflow, but I couldn't really find the thing I need.

1
  • Can you use '--d' as the default 'store' Action? Commented Jun 27, 2019 at 16:35

1 Answer 1

1

To make an optional argument take a value you have to add it like this:

parser.add_argument("--d", nargs=1)

it means that if --d is specified than it needs one (and only one) value. nargs keyword can also have *, ?, + for different type of optional values.
Default value for --d when not specified will be None but this can be changed with default=False.

# --a doesn't need a value
>>> parser.parse_args('--a'.split())
Namespace(a=True, b=False, c=False, d=None)

# --d does need a value
>>> parser.parse_args('--d'.split())
usage: [-h] [--a] [--b] [--c] [--d D]
: error: argument --d: expected 1 argument

>>> parser.parse_args('--d VALUE'.split())
Namespace(a=False, b=False, c=False, d=['VALUE'])

When specified, --d value will always be type of list with a single string (for nargs=1).

Also because you are using -- with single letter arguments it makes them long optional arguments that cannot be stacked together. If you change it to - you can run your program like this:

>>> parser.parse_args('-abcd VALUE'.split())
Namespace(a=True, b=True, c=True, d=['VALUE'])
Sign up to request clarification or add additional context in comments.

1 Comment

full answer, well written. I think, I will improve my code with your suggestions. I have already solved my problem by just removing the "action=..." part, but again, your answer will be selected as the answer, since you provided additional information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.