2012-05-03 201 views
0

幫我弄清楚當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 
+1

不要使用裸'except'。聲明你想要捕捉的類型。 – Daenyth

回答

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 
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) 

一般來說,除非你使用控制流異常,則應該儘快合理,防止與其他混合例外抓到。你也應該明確你想要捕捉什麼異常,而不是捕捉一些通用的東西。