如何在Python应用程序中将条件指令块简化为一个elif语句?

时间:2018-11-01 14:22:29

标签: python cmd lan

我写了一个简单的应用程序,它可以对我学校计算机实验室的本地网络中的计算机执行ping操作,然后重新启动/关闭它们,或者一一关闭。该应用程序运行良好,但其中包含分配给实验室中指定计算机(有18台计算机)的大量elif语句:

def shutdown_all():
    with open(os.devnull, "wb"):
        for computer in range(1, 19):
            ip = "pracownia{0}".format(computer)
            subprocess.call('shutdown -s -t 0 /m \\\\%s' % ip)
    print("\nTask complete\n")


def shutdown_selected(ip):
    with open(os.devnull, "wb"):
        machine = "pracownia{0}".format(ip)
        subprocess.call('shutdown -s -t 0 /m \\\\%s' % machine)
    print("\nTask complete\n")


while True:
    mode = input()
    if mode == 'exit':
        break
    elif mode == "shutdown -all":
        shutdown_all()
    elif mode == "shutdown -ip 1":
        shutdown_selected(1)
    elif mode == "shutdown -ip 2":
        shutdown_selected(2)
    elif mode == "shutdown -ip 3":
        shutdown_selected(3) 

        ...

    else:
        print("Wrong mode. Type valid command.")

是否可以简化指令并将整个块简化为一个elif语句,从而允许用户输入要ping /重启/关机的计算机?

3 个答案:

答案 0 :(得分:1)

减少大型if-else树的复杂性的常用方法是使用字典。但是,您会将复杂性转移到其他地方。例如:

options = dict(foo = foo, bar = bar, foobar = foobar)
options.get(input("Enter an option"), print('Input is not an option'))

此示例显示,对于三个不同的选项关键字,您具有三个不同的功能。方法 get 将在字典中查找该选项,否则将打印并显示错误消息。

关于您的代码,我会将复杂性转移给一个函数,如下所示:

def shutdown(command):
    computers = set(str(i) for i in range(1,19))

    with open(os.devnull, "wb"):
        selecComputers = set(command.split(' ')[2:]) # or use regex
        if len(selectComputers) > 0:
           computers = computers.intersection(selectComputers)
        for computer in computers:
            ip = "pracownia{0}".format(computer)
            subprocess.call('shutdown -s -t 0 /m \\\\%s' % ip)
    print("\nTask complete\n")

while True:
    mode = input()
    if mode == 'exit':
        break
    elif 'shutdown' in mode:
        shutdown(mode)
    else:
        print("Wrong mode. Type valid command.")

答案 1 :(得分:1)

与先前的答案相同,但使用正则表达式进行解析,因为IP可以为1-2位数字。

import re
mode = input()
if mode == 'exit'
    break
elif mode == 'shutdown -all'
    shutdown_all()
elif mode[:12] == 'shutdown -ip':
    match = re.search(r'\d+', mode)
    if match:
        ip = match.group()
        shutdown_selected(ip)

答案 2 :(得分:0)

您能不能做类似的事情?

mode = input()
if mode == 'exit'
    break
elif mode == 'shutdown -all'
    shutdown_all()
elif mode[:12] == 'shutdown -ip':
    shutdown_selected(int(mode[-1:]))

您可以在最后一个elif语句中添加一些内容,以确保它们键入的内容适用于您的功能-是您需要的吗?