我已经浏览了很长时间来寻找这个问题的答案。
我在 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
几次,但似乎没有一个像我希望的那样工作。
最佳答案
>>> try:
... print 'Ctrl-C to end'
... while(True):
... pass
... except KeyboardInterrupt, e:
... print 'Stopped'
... raise
...
Ctrl-C to end
Stopped
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
>>>
显然,您需要用您正在做的任何事情替换 pass 并打印后果。
关于python - 在python中使用用户提示退出while循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17972674/