如何在 python 中等待输入而不阻塞计时器?

How to wait for an input without blocking timer in python?

我需要每隔 x 秒打印一条消息,同时,我需要听取用户的输入。如果按下 'q',它应该终止程序。

例如

some message
.
. # after specified interval
. 
some message
q # program should end

我现在面临的当前问题是 raw_input 正在阻塞,这会阻止我的函数重复消息。如何并行获取输入读数和函数 运行?

编辑:原来 raw_input 没有阻塞。我误解了多线程的工作原理。我会把它留在这里,以防有人偶然发现它。

您可以使用线程在不同的线程中打印消息。

import threading

t = threading.Timer(30,func,args=[])
t.start()

其中 30 是调用 func 的频率。

func 是在不同线程中调用的函数。

args 是调用函数的参数数组

如果您只想调用一个不同的函数,您可以这样做

t = threading. Thread(target=func, args=[]) 
t.start() 

这将使 func 运行 并行

import threading
import time as t

value = 0

def takeInput():
    """This function will be executed via thread"""
    global value
    while True:
        value = raw_input("Enter value: ")
        if value == 'q':
            exit()  # kills thread
        print value
    return

if __name__ == '__main__':
    x = int(raw_input('time interval: '))
    thread = threading.Thread(target=takeInput)
    thread.start()
    while True:
        if value == 'q':
            exit()  # kills program
        print 'some message'
        t.sleep(x)