PDA

View Full Version : How to do this in Python?



kevin11951
April 13th, 2011, 09:55 PM
How do I make Python listen for external input while running? I don't mean "raw_input()", I mean where the program will be running happily, and then if I press "q" while its running, it quits... Or something along those lines...

ssam
April 13th, 2011, 10:02 PM
simplest method is to catch the KeyboardInterrupt exception that is generated when the user presses ctrl+C



try:
code_that_takes_long_time()
except KeyboardInterrupt:
print "stopped"
clean_up()


otherwise you may need to look at a terminal handling library like curses.

kevin11951
April 13th, 2011, 11:08 PM
simplest method is to catch the KeyboardInterrupt exception that is generated when the user presses ctrl+C



try:
code_that_takes_long_time()
except KeyboardInterrupt:
print "stopped"
clean_up()


otherwise you may need to look at a terminal handling library like curses.

So there is no way to do two things at once in Python?

ssam
April 13th, 2011, 11:53 PM
you can use threads.