Reputation: 1339
I have a python parsing arguments like below:
Code:
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Args test')
parser.add_argument('-myarg1', '--myarg1', type=str, dest='myarg1', required=True, help='Help yourself')
parser.add_argument('-myarg2', '--myarg2', type=str, dest='myarg2', default=' ', help='Help yourself')
args = parser.parse_args()
print(args.myarg1)
print(args.myarg2)
Above works if I call the script like below:
python myargs.py -myarg1 something -myarg2 somethingelse
But it does not work if I call it like below:
python myargs.py -myarg1 something -myarg2
And throws the below error obviously because it expects caller to pass value for the second argument.
usage: myargs.py [-h] -myarg1 MYARG1 [-myarg2 MYARG2]
myargs.py: error: argument -myarg2/--myarg2: expected one argument
Quesion:
I understand the reason for python complaining about it above. But, I want the user of my python script to be able to call the second argument with just saying -myarg2
or --myarg2
without specifying the type. Just like shell script style. Is it possible to do it with argparse
?
I am using python 2.7 and above.
Upvotes: 1
Views: 1219
Reputation: 231
It is possible. You can use the action="store_true"
attribute to turn an argument into a Boolean (flag).
parser.add_argument('-myarg2', '--myarg2', dest='myarg2', action="store_true", help='Help yourself')
args = parser.parse_args()
print(args.myarg2) # True if "python myargs.py -myarg2", False if "python myargs.py"
If you want the user to be able to pass an optional argument to the myarg2
flag, you need to use the nargs='?'
attribute. You also need to define a default
attribute which will be called if the flag isn't used, and a const
attribute which will be called if the flag is used but without arguments.
parser.add_argument('-myarg2', '--myarg2', dest='myarg2', nargs='?', const="no value", default='no flag', help='Help yourself')
Upvotes: 2
Reputation: 5735
if you want to use --myarg and interpret it as true (otherwise it is false) you need to use
parser.add_argument("-myarg2", "--myarg2", action="store_true")
Upvotes: 1
Reputation: 6181
The problem is that you call the argument flag without a value. If you want the value to be an empty string do -
python myargs.py -myarg1 something -myarg2 ' '
Upvotes: 1