2

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

hadi zahir
  • 21
  • 1
  • What have you tried so far? For a rational number you could pass in two arguments, a numerator and a denominator. For an irrational number you are out of luck because you could only pass in the closest representation as a floating point value - e.g. 3.151592654 etc. Unless you want to create an argument (-irrat for example) that has a specific set of enumerated definitions like 'pi' and 'root2' or something. But then when translating these internally you'll still end up with a floating point representation. – Tom Johnson Dec 28 '18 at 20:55

1 Answers1

1

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.

hpaulj
  • 221,503
  • 14
  • 230
  • 353