0

I have a very simple python program which takes two command line arguments one required n and other optional m whose default value is 1. The product of the two is printed out.

multiply_number.py

# CLI to multiply a number by another
import argparse

parser = argparse.ArgumentParser(
    description='Multiplies the input <n> by <m>')

parser.add_argument(
    'n', type=float, help='Input number to be multiplied'
)
parser.add_argument(
    '-m', '--multiplier',
    type=float,
    default=1,
    help='multiplier for <n>: (default: 1)'
)

namespace = parser.parse_args()
n, m = namespace.n, namespace.multiplier

res = n*m
print(res)

Currently the way to execute this program is in the following ways:

~$ python multiply_number.py 5 
5.0
~$ python multiply_number.py 5 -m 2
10.0
~$ python multiply_number.py 5 --multiplier 2
10.0

However in addition to above, I want it to run in the following manners as well:

~$ python multiply_number.py 5 2
10.0
~$ python multiply_number.py -n 5 -m 2
10.0
~$ python multiply_number.py -number 5 --multiplier 2
10.0

Basically, I want it to work with and without flags for both required and optional argument. If possible suggest solutions in argparse.

Abhishek Bhatia
  • 547
  • 4
  • 11
  • 1
    Why? Positional arguments have traditionally been *required* arguments. To use both command-line switches *and* positional arguments for the same value is really confusing UI. – Martijn Pieters Aug 10 '19 at 18:31
  • Basically, argparse doesn't support this use case. You'd have to use both a positional argument *and* the command line switch then make them mutually exclusive. Not sure if the [existing mutually exclusive group option](https://docs.python.org/3/library/argparse.html#mutual-exclusion) lets you mix argument types. – Martijn Pieters Aug 10 '19 at 18:32
  • You can do it, but your parser definition, and post parsing processing will be messier. Just define a couple of other arguments. – hpaulj Aug 10 '19 at 20:15
  • This is what you looking for, just adapt it. https://stackoverflow.com/questions/15301147/python-argparse-default-value-or-specified-value – vimeo May 06 '20 at 23:48

0 Answers0