在Python中输入时停止

时间:2010-10-17 23:15:09

标签: python loops

如何在Python中运行循环并将其编码为用户按下按钮(不是ctr + c)时停止?

1 个答案:

答案 0 :(得分:0)

我有类似的问题,发现这段代码摘录帮助了我。

#!/usr/bin/env python
import curses

def main(win):
win.nodelay(True) # make getkey() not wait
x = 0
while True:
    #just to show that the loop runs, print a counter
    win.clear()
    win.addstr(0,0,str(x))
    x += 1

    try:
        key = win.getkey()
    except: # in no delay mode getkey raise and exeption if no key is press 
        key = None
    if key == " ": # of we got a space then break
        break

#a wrapper to create a window, and clean up at the end
curses.wrapper(main)

问题当然是使用curses会阻止许多其他事情(比如打印)的工作,但有很多方法。