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

我只想一次显示“找到”否则“未找到”

4

4 回答 4

1

另一种方法是使用一个函数并在你有 print 的地方替换 return。您可以利用 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()
于 2012-07-28T17:32:17.323 回答
0

您必须在“if”案例之后添加“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

            #added here
            break

        else:
            print "Not found"
            break

这将打破“('Caption','Capabilities')”的迭代

于 2012-07-28T12:51:11.443 回答
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
于 2012-07-28T12:52:28.553 回答
0

展示?你的意思是执行,我想。只需将 break 放在 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 anser

于 2012-07-28T12:53:13.410 回答