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
.