2012-07-28 58 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()