Zvo*_*ran 14 python command-line
我试图使用我的程序与命令行选项.这是我的代码:
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()
Run Code Online (Sandbox Code Playgroud)
当我尝试从终端(python script.py -u)运行我的程序时,我希望得到消息Starting with upgrade procedure,但我收到错误消息unrecognized arguments -u.
Rak*_*ish 16
你得到的错误是因为-u期待它后面有一些值.如果您使用,python script.py -h您会在使用声明中找到它[-u UPGRADE].
如果要将其用作布尔值或标志(如果-u使用,则为true ),请添加其他参数action:
parser.add_argument("-u","--upgrade", help="fully automatized upgrade", action="store_true")
Run Code Online (Sandbox Code Playgroud)
action - 在命令行遇到此参数时要采取的基本操作类型
使用action="store_true",如果-u指定了该选项,则赋值为True args.upgrade.不指定它意味着False.