How can I feed rational numbers like 3/2, through terminal, into my python script using argparse? I have the same problem when I want to input pi or any other irrational numbers like sqrt(2) using argparse.
Regards, Hadi
How can I feed rational numbers like 3/2, through terminal, into my python script using argparse? I have the same problem when I want to input pi or any other irrational numbers like sqrt(2) using argparse.
Regards, Hadi
With
import argparse
import sys
print(sys.argv)
parser = argparse.ArgumentParser()
parser.add_argument('aNumber')
args = parser.parse_args()
print(args)
sample runs:
1414:~/mypy$ python3 stack53964076.py -h
['stack53964076.py', '-h']
usage: stack53964076.py [-h] aNumber
positional arguments:
aNumber
optional arguments:
-h, --help show this help message and exit
1417:~/mypy$ python3 stack53964076.py 3/2
['stack53964076.py', '3/2']
Namespace(aNumber='3/2')
1417:~/mypy$ python3 stack53964076.py pi
['stack53964076.py', 'pi']
Namespace(aNumber='pi')
1417:~/mypy$ python3 stack53964076.py sqrt(2)
bash: syntax error near unexpected token `('
1417:~/mypy$ python3 stack53964076.py 'sqrt(2)'
['stack53964076.py', 'sqrt(2)']
Namespace(aNumber='sqrt(2)')
In all these cases args.aNumber
will be a string. In the last case I had to include quotes to prevent the shell from trying to parse the '(' itself.
Handling these strings is the responsibility of your own code, not argparse
.