我正在尝试将我的程序与命令行选项一起使用。这是我的代码:
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
。
您得到的错误是因为
-u
后面需要某个值。如果您使用python script.py -h
,您将在usage语句中找到它,并显示[-u UPGRADE]
。如果要将其用作布尔值或标志(如果使用
-u
,则为true),请添加一个附加参数action
:action
-在命令行遇到此参数时要采取的基本操作类型使用
action="store_true"
,如果指定了选项-u
,则将值True赋给args.upgrade
。不指定它意味着错误。来源:Python argparse documentation
目前,您的参数还需要传入一个值。
如果希望} 作为不需要值的参数。
-u
作为选项,请使用^{示例-
对于布尔参数,请使用action=“store\u true”:
见:https://docs.python.org/2/howto/argparse.html#introducing-optional-arguments
相关问题 更多 >
编程相关推荐