Python argparse:“无法识别的参数”

2024-06-17 08:12:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将我的程序与命令行选项一起使用。这是我的代码:

import argparse

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("-u","--upgrade", help="fully automatized upgrade")
    args = parser.parse_args()

    if args.upgrade:
        print "Starting with upgrade procedure"
main()

当我试图从终端(python script.py -u)运行我的程序时,我希望得到消息Starting with upgrade procedure,但是我得到的是错误消息unrecognized arguments -u


Tags: 代码命令行import程序parser消息maindef
3条回答

您得到的错误是因为-u后面需要某个值。如果您使用python script.py -h,您将在usage语句中找到它,并显示[-u UPGRADE]

如果要将其用作布尔值或标志(如果使用-u,则为true),请添加一个附加参数action

parser.add_argument("-u","--upgrade", help="fully automatized upgrade", action="store_true")

action-在命令行遇到此参数时要采取的基本操作类型

使用action="store_true",如果指定了选项-u,则将值True赋给args.upgrade。不指定它意味着错误。

来源:Python argparse documentation

目前,您的参数还需要传入一个值。

如果希望-u作为选项,请使用^{}作为不需要值的参数。

示例-

parser.add_argument("-u","--upgrade", help="fully automatized upgrade", action='store_true')

对于布尔参数,请使用action=“store\u true”:

parser.add_argument("-u","--upgrade", help="fully automatized upgrade", action="store_true")

见:https://docs.python.org/2/howto/argparse.html#introducing-optional-arguments

相关问题 更多 >