如何使用用户输入退出Double For Loop

时间:2019-04-11 16:23:29

标签: python-2.7 loops msvcrt

我有一个代码块,其中包含2个For循环,并且执行深字符串匹配。当条件调用此搜索时,我希望用户从此循环中获得“退出”,因为它可以长时间运行。我发现,平均而言,当我的代码到达此搜索时,通常可以在2到15秒内找到匹配项,或者根本不找到匹配项。

我在网上找到了有关使用msvcrt.kbhit()和getche()来允许击键的代码。我已经尝试了所有可以想到的变体,但是我遇到了同样的几个问题。

  1. 我要运行以执行深度潜水搜索的代码会运行并找到匹配项,并且永远不会自行退出。

  2. 与1相同,但将等我按Enter退出不正确的循环。

  3. 代码将运行,自行找到匹配项并退出,然后在无法找到匹配项的输入上进行测试,并且“ enter”出口将不起作用。

我正在寻找我的double for循环,而当前中断使我们陷入循环,这使得将所有内容放置在正确的位置变得很困难。任何帮助将不胜感激!

最后。我希望我的double for循环在找到匹配项后运行并中断,并继续尝试进行匹配,直到确实发生或用户按下Enter退出。

原始问题代码:

if foundHeadline == False:
    print 'Still didnt find Headline and performing a deep dive search'
    find = False
    keyboard = Controller()
    # startTime = time.time()
    # elapsed = 0
    # while elapsed < 10:
    # userinput = raw_input("Press Enter to Stop Search: ")
    running = 0
    print 'Press Enter to Exit Search . . .'

    # findVariable = False
    while not msvcrt.kbhit() or msvcrt.getche() != '\r':
        for i in range(15):
            headlineFound = 0
            for subset in itertools.combinations(itemsList, i):
                if ''.join(subset) == cmcHeadline:
                    # print(''.join(subset))
                    headlineFound += 1
                    if headlineFound == 2:
                        print 'Deep Dive Headline Found: ', ''.join(subset)
                        find = True
                        foundHeadline = True
                        keyboard.press('\r')
                        keyboard.release('\r')
                        # findVariable = True
                        break
            if find:
                break
        if msvcrt.getche() == '\r':
            print 'Breaking out of Search'

更新的解决方案代码

if foundHeadline == False:
    print 'Still didnt find Headline and performing a deep dive search'

    find = False
    keyboard = Controller()

    print 'Press "Ctrl + C" to exit the search. . .'
    print ''

    try:
        while True:
            for i in range(15):
                headlineFound = 0
                for subset in itertools.combinations(itemsList, i):
                    if ''.join(subset) == cmcHeadline:
                        # print(''.join(subset))
                        headlineFound += 1
                        if headlineFound == 2:
                            print 'Deep Dive Headline Found: ', ''.join(subset)
                            find = True
                            foundHeadline = True
                            print ''
                            keyboard.press(Key.ctrl.value)
                            keyboard.press('c')
                            keyboard.release('c')
                            keyboard.release(Key.ctrl.value)
                            break
                if find:
                    break
    except KeyboardInterrupt:
        pass

0 个答案:

没有答案