简体   繁体   English

如何在 Python 中使用 argparse 传递 Shell 脚本样式参数

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

I have a python parsing arguments like below:我有一个 python 解析参数,如下所示:

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.我理解python在上面抱怨它的原因。 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.但是,我希望我的 python 脚本的用户能够只说-myarg2--myarg2而不指定类型来调用第二个参数。 Just like shell script style.就像shell脚本风格一样。 Is it possible to do it with argparse ?可以用argparse来做吗?

I am using python 2.7 and above.我正在使用 python 2.7 及更高版本。

It is possible.有可能的。 You can use the action="store_true" attribute to turn an argument into a Boolean (flag).您可以使用action="store_true"属性将参数转换为布尔值(标志)。

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='?'如果您希望用户能够将可选参数传递给myarg2标志,则需要使用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.您还需要定义一个default属性,如果未使用标志,则将调用该属性,以及在使用标志但没有参数时调用的const属性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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