异常后继续
问题描述:
帮我弄清楚当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
答
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
答
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)
一般来说,除非你使用控制流异常,则应该尽快合理,防止与其他混合例外抓到。你也应该明确你想要捕捉什么异常,而不是捕捉一些通用的东西。
不要使用裸'except'。声明你想要捕捉的类型。 – Daenyth