2

Consider three different runs of a program:

python3 prog.py
python3 prog.py --x
python3 prog.py --x 2

Is it possible to use argparse such that, for example, in the first case, x==None, in the second case, x==1, and in the third, x==2?

2 Answers 2

4

nargs'?' with a const parameter handles this 3-way input nicely..

In [2]: parser = argparse.ArgumentParser()
In [3]: parser.add_argument('-x','--x', nargs='?', type=int, const=1)
...
In [4]: parser.parse_args([])
Out[4]: Namespace(x=None)
In [5]: parser.parse_args(['-x'])
Out[5]: Namespace(x=1)
In [6]: parser.parse_args(['-x','2'])
Out[6]: Namespace(x=2)

I could have also given it a default parameter.

how to add multiple argument options in python using argparse?

Sign up to request clarification or add additional context in comments.

2 Comments

+1 I did not know about this usage of const. I'd give away the check-mark if I could, hopefully OP will see this and change their accepted answer.
This nargs='?' combined with const is brilliant!
2

You may want to consider instead the count action, which is commonly used to specify verbosity levels. The usage is different, for example:

python3 prog.py
python3 prog.py -v
python3 prog.py -vv

Comments

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.