简体   繁体   中英

How to make Shell script style arguments passing with argparse in Python

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.

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"

Edit

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')

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 ' '

如果您想使用 --myarg 并将其解释为真(否则为假),您需要使用

parser.add_argument("-myarg2", "--myarg2", action="store_true")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM