i am trying to use python argparse in the following code. I want the user to enter the text as below. -x 8 -l 9 -b 20
import argparse
parser = argparse.ArgumentParser(description='Sample coding with arguments')
parser.add_argument('-x', '--height', help='Height of the box')
parser.add_argument('-l', '--length', type=int, help='Length of the box')
parser.add_argument('-b', '--breadth', type=int, help='Breadth of the box')
args = parser.parse_args([input("enter text: ")])
print (args)
the user should only enter these data when the system ask to enter. the following code work if i enter a value for only 1 argument. But is not working if i use more than 1. With two arguments it is showing this result
enter text: -x 9 -l 7
Namespace(height=' 9 -l 7', length=None, breadth=None)
Both value was assigned to height.
When you run a python script with arguments from the command line, say:
test.py -x 9 -l 7
The interpreter has a sys.argv
of
sys.argv == ["test.py", "-x", "9", "-l", "7"]
By default argparse is provided sys.argv[1:]
or ["-x", "9", "-l", "7"]
You provided ["-x 9 -l 7"]
Instead you need to split the string:
parser.parse_args(input("enter text: ").split())