【发布时间】:2013-07-31 23:28:57
【问题描述】:
我已经浏览了很长时间来寻找这个问题的答案。
我在 Unix 中使用 Python 2.7。
我有一个连续的while循环,我需要一个选项,用户可以中断它,做一些事情,然后循环将继续。
喜欢:
while 2 > 1:
for items in hello:
if "world" in items:
print "hello"
else:
print "world"
time.sleep(5)
here user could interrupt the loop with pressing "u" etc. and modify elements inside he loop.
我开始使用 raw_input 进行测试,但由于它会在每个周期都提示我,所以我不需要它。
我试过这里提到的方法:
Keyboard input with timeout in Python
几次,但似乎都没有按照我的意愿工作。
【问题讨论】:
-
您希望它如何工作?我想那时只有一个词适合你:线程。
-
为什么要使用
while 2>1而不是while True? -
raw_input()无法读取一个字符,因为“普通”控制台输入是行缓冲的。请参阅此无缓冲阅读配方code.activestate.com/recipes/134892 -
我在原始代码中使用了 True。感谢您提及线程。我会调查这些。
-
信号方法(在您链接到的问题中讨论过)对您不起作用怎么办?看来这应该是一个可行的解决方案...否则,您可以尝试使用 select (docs.python.org/release/2.5.2/lib/module-select.html) 来轮询键盘,看看它是否有任何新的输入。
标签: python