在等待用户输入时运行循环

Dri*_*itz 5 python loops

我想在我的脚本中运行一个循环,而用户没有输入任何内容。但是当他们输入一些东西时,我希望循环中断。

我目前遇到的问题是,在使用该input()函数时,脚本将停止并等待输入,但我想在等待用户输入的同时运行脚本的另一部分。

我已经尝试使用try:raw_input()

while True:
    try:
        print('SCAN BARCODE')
        userInput= raw_input()
        #doing something with input
    except:
        #run this while there is no input
Run Code Online (Sandbox Code Playgroud)

有了这个,我发现无论在什么都except:将始终运行,但try:即使有用户输入它也不会运行。如果我改变raw_input()input()剧本只是等待的input()和不运行的任何东西except:

我如何实现我所追求的?

rus*_*ro1 6

你可以使用 python 线程:

from threading import Thread
import time

thread_running = True


def my_forever_while():
    global thread_running

    start_time = time.time()

    # run this while there is no input
    while thread_running:
        time.sleep(0.1)

        if time.time() - start_time >= 5:
            start_time = time.time()
            print('Another 5 seconds has passed')


def take_input():
    user_input = input('Type user input: ')
    # doing something with the input
    print('The user input is: ', user_input)


if __name__ == '__main__':
    t1 = Thread(target=my_forever_while)
    t2 = Thread(target=take_input)

    t1.start()
    t2.start()

    t2.join()  # interpreter will wait until your process get completed or terminated
    thread_running = False
    print('The end')
Run Code Online (Sandbox Code Playgroud)

在我的示例中,您有 2 个线程,第一个线程启动并执行代码,直到您有来自用户的一些输入,线程 2 正在等待来自用户的一些输入。获得用户输入后,线程 1 和 2 将停止。