0

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

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
4

2 回答 2

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)

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

于 2012-05-03T15:18:02.777 回答
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
于 2012-05-03T15:16:25.683 回答