![](/img/trans.png)
[英]How to use a timer or equivalent within a python thread without blocking the GUI
[英]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()
哪里叫func的频率是30。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.