user1717079
user1717079

Reputation: 523

Stopping python loop on key pressed

with 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 ?

I would like to have an infinite loop and break it only when the user press some specific key or any key.

Upvotes: 0

Views: 1940

Answers (2)

Harman
Harman

Reputation: 1581

One more approach is Async. user input. In your case a db or a simple file would suffice.

Have a look at this question

Upvotes: 3

user1717079
user1717079

Reputation: 523

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.

Upvotes: 1

Related Questions