异常后继续

时间:2012-05-03 15:12:43

标签: python wmi

帮助我弄清楚当WMI无法连接到主机并转到列表中的下一台计算机时,脚本将如何继续运行。除了以后我应该继续使用吗?

import wmi
MachineList = ["Computer1","Computer2","Computer3"]
try:
    for machines in MachineList:
        c = wmi.WMI(machines) # <---- Go to next in the for loop when connection fail???
        for os in c.Win32_OperatingSystem():
            print os.Caption
except:
    pass

2 个答案:

答案 0 :(得分:4)

import wmi
MachineList = ["Computer1","Computer2","Computer3"]
for machines in MachineList:
    try:
        c = wmi.WMI(machines) # <---- Go to next in the for loop when connection fail???
        for os in c.Win32_OperatingSystem():
            print os.Caption
    except Exception: #Intended Exception should be mentioned here
        print "Cannot Connect to {}".format(machines)

一般来说,除非您使用控制流程的例外,否则应尽快将其捕获,以防止与其他异常混合。此外,您应该具体说明要捕获的异常,而不是捕捉通用的内容。

答案 1 :(得分:0)

for machine in MachineList:
    try:
        c = wmi.WMI(machine)
        for os in c.Win32_OperatingSystem():
            print os.caption
    except Exception:
        print "Failed on machine %s" % machine