【发布时间】:2014-10-10 20:47:19
【问题描述】:
在 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是一个不错的选择。