简体   繁体   English

在按下键时停止python循环

[英]Stopping python loop on key pressed

with python 2.7 使用python 2.7

import time, os

def foo():
    try:
        a=0
        while 1:
            os.system("bash command")
            a += 1
            time.sleep(1/30)
        print a
    except KeyboardInterrupt:
        print "Interrupted!"

foo()

I'm running this from a terminal under Ubuntu 12.04 64 bit but i can't stop this infinite loop, why it's not working ? 我正在Ubuntu 12.04 64位下的终端上运行此程序,但是我无法停止此无限循环,为什么它不起作用?

I would like to have an infinite loop and break it only when the user press some specific key or any key. 我想有一个无限循环并仅在用户按下某些特定键或任何键时才将其中断。

One more approach is Async. 另一种方法是异步。 user input. 用户输入。 In your case a db or a simple file would suffice. 在您的情况下,一个数据库或一个简单的文件就足够了。

Have a look at this question 看看这个问题

Problem solved. 问题解决了。

Due to the low value of time.sleep() the execution of the loop was almost impossible to stop, apparently with an higher value for the sleep() the application is more responsive to the user input and everything works. 由于time.sleep()的值较低,因此几乎不可能停止循环的执行,显然,对于sleep()而言,该值较高,因此应用程序对用户输入的响应更高,并且一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM