在Python中输入时停止

问题描述:

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

+0

这取决于。你想让它成为一个*运行的循环,或者每次通过循环等待一些用户输入的循环吗?而且,什么样的按钮输入?鼠标按钮?键盘?电源按钮? – 2010-10-17 23:20:41

+4

可能的解决方案:http://*.com/questions/3894408/easiest-way-to-pause-a-command-line-python-program/3894439#3894439。链接代码中的小改动可以使程序在按下按键时暂停/取消暂停。 – unutbu 2010-10-17 23:21:19

+0

我想要一个*运行的循环。输入可以是任何人或特定的。但是,这可能吗? – FRD 2010-10-17 23:41:03

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

#!/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) 

当然,问题在于,使用诅咒将会阻止很多其他的事情(比如印刷)的工作,但也有周围的方式。