在Python中,我可以通过什么方式在循环中做些什么,而用户还没有给出输入。 我有python客户端,我要求用户输入,但虽然用户没有给出输入,但我希望每五秒钟更新一次。在用户输入没有收到的时候做点什么
我不能使用
while (raw_input==""):
update()
,因为如果输入“”,这意味着用户已经输入的东西(按回车键);
有没有办法做到这一点?
更新:
我仍然无法为我工作得到任何东西。我试过下面的方法,也试过类似于这个线程的东西:waiting for user input in separate thread。我也尝试将update()方法传递给应该在后台工作的线程。但随着事情的raw_input()使得它停留在等待输入:
import threading
import time
def update():
while True:
time.sleep(5)
print "update"+'\n'
mythread = threading.Thread(target=update, args=())
mythread.daemon = True
mythread.start()
while True:
usrin=raw_input()
print "you typed: "+usrin
每当用户输入的东西,更新完成,然后usrin给出了回来。如果这是我想要的,我可以轻松地将update()放入最后一个while循环中。
如果我只是用update方法启动这个线程,并在程序中不做任何其他操作(废弃最后一个while循环),那么在shell中每隔五秒更新一次,我仍然可以使用shell(即类型3+ 5,它给了我8)。我希望在程序中发生类似的情况,当用户不活动更新时,以及他是否反应并返回更新。
注意:另外,我目前使用python 2.7.8,切换版本有帮助吗?
也许使用'thread'是一个不错的选择。 – 2014-10-10 20:52:06
https://docs.python.org/2/library/threading.html https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing – 2014-10-10 20:55:15