在这段代码中如何使用python找到或找不到字符串后停止

时间:2012-07-28 12:43:28

标签: python

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 个答案:

答案 0 :(得分:1)

另一种方法是使用一个函数,并在有打印的地方替换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()

答案 1 :(得分: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')”

答案 2 :(得分: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

答案 3 :(得分: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 anser