2012-07-28 24 views
0
import win32com.client 
objSWbemServices = win32com.client.Dispatch(
    "WbemScripting.SWbemLocator").ConnectServer(".","root\cimv2") 
for item in objSWbemServices.ExecQuery(
     "SELECT * FROM Win32_PnPEntity "): 
    found=False 
    for name in ('Caption','Capabilities '): 
     a = getattr(item, name, None) 
     if a is not None: 
      b=('%s,' %a) 
      if "Item" in b: 
       print "found" 
       found = True 

      else: 
       print "Not found" 
       break 

我只想要一次顯示「發現」找不到串別的「未找到」在這段代碼如何停止後發現或使用python

回答

0

你後面添加「破發」,「如果」情況是這樣的:

for name in ('Caption','Capabilities '): 
    a = getattr(item, name, None) 
    if a is not None: 
     b=('%s,' %a) 
     if "Item" in b: 
      print "found" 
      found = True 

      #added here 
      break 

     else: 
      print "Not found" 
      break 

這將爆發迭代過的 「( '標題', '能力')」

0

移動break一個壓痕電平向上:

for name in ('Caption','Capabilities '): 
    a = getattr(item, name, None) 
    if a is not None: 
     b=('%s,' %a) 
     if "Item" in b: 
      print "found" 
      found = True 
     else: 
      print "Not found" 

     break 
+0

事實上,我想打印「未找到」多次,只有一次我打印 – user1556698 2012-07-28 12:57:42

0

顯示?你的意思是執行,我想。 只要把它放在else語句的外部(如果a不是None的話)。以這種方式,如果a不是none,那麼只要「Item」在b中,循環就會停止。

for name in ('Caption','Capabilities '): 
    a = getattr(item, name, None) 
    if a is not None: 
     b=('%s,' %a) 
     if "Item" in b: 
      print "found" 
      found = True 

     else: 
      print "Not found" 
     break 

編輯:見warwaruk雁

+0

事實上,我想打印「未找到」不是多次只有一次我必須打印 – user1556698 2012-07-28 13:01:14

+0

這段代碼打印「發現「或」找不到「(取決於'如果'項目在b:')只有一次。 – 2012-07-28 13:04:57

+0

如果物品沒有找到應該如何停止循環 – user1556698 2012-07-28 13:07:46

1

另一種方式做,這是使用功能和替代的回報,你必須打印。您可以利用python中的函數在返回時停止執行的事實。

def finder(): 
    objSWbemServices = win32com.client.Dispatch(
     "WbemScripting.SWbemLocator").ConnectServer(".","root\cimv2") 
    for item in objSWbemServices.ExecQuery(
     "SELECT * FROM Win32_PnPEntity "): 
     for name in ('Caption','Capabilities '): 
      a = getattr(item, name, None) 
      if a is not None: 
       b=('%s,' %a) 
       if "Item" in b: 
        return True # or return "Found" if you prefer 
       else: 
        return False # or return "Not Found" if you prefer 

found = finder() 
print found 
# or 
print finder() 
相關問題