在继续之前让Python确认是否/ Elif / Else

时间:2017-08-25 14:43:51

标签: python if-statement

我编写了一个简单的python脚本来获取命令行参数并将它们写入文件,以便使用Ansible部署到路由器。但在我的脚本创建输出文件之前,我想强制用户使用Y / N(是或否)条目确认请求。

如何修改此脚本以在每个if / elif语句之后请求?

#!/usr/bin/python

import argparse
import sys

parser = argparse.ArgumentParser()
parser.add_argument("-s", "--set", help="set", action="store_true")
parser.add_argument("-d", "--delete", help="delete", action="store_true")
parser.add_argument("-i", "--ipaddr", help="Target IP")
args = parser.parse_args()
if args.set:
        print "Deploying: set routing-options static route %s" % (args.ipaddr)
        filename = open("/var/tmp/output.txt",'w')
        sys.stdout = filename
        print "set routing-options static route %s" % (args.ipaddr)
elif args.delete:
        print "Deploying: delete routing-options static route %s" % (args.ipaddr)
        filename = open("/var/tmp/output.txt",'w')
        sys.stdout = filename
        print "delete routing-options static route %s" % (args.ipaddr)
else:
        exit(1)

1 个答案:

答案 0 :(得分:1)

只需编写ask_confirm函数并在需要的地方调用它:

def ask_confirm(msg="Are you sure?"):
    answer = ""
    while answer not in ("yes", "no"):
        answer = input(msg + " [yes/no]")
    return (True if answer == "yes" else False)

msg的默认值允许您使用通用消息调用ask_confirm。 它返回一个布尔值,因此更容易处理。 如果需要,可以以更高级的方式定制输入。 这是一个更高档的版本:

def ask_confirm(msg="Are you sure?", yes=None, no=None):
    if yes is None:
        yes = ["yes"]
    if no is None:
        no = ["no"]
    if isinstance(yes, str):
        yes = [yes]
    if isinstance(no, str):
        no = [no]

    answer = ""
    while answer not in yes and answer not in no:
        answer = input(msg + " [{}/{}]".format(yes[0], no[0]))
    return (True if answer in yes else False)

然后你可以在每个区块的开头要求确认:

if args.set:
    if not ask_confirm("Do you really want to set?"):
        sys.exit()
    # else (not needed)
    # proceed

elif args.delete:
    if not ask_confirm("Are you sure you want to delete?"):
        sys.exit()
    # else (not needed)
    # proceed

else:
    sys.exit(1)