PDA

View Full Version : Exit a continuous python script with key press?



OldGregory
November 29th, 2008, 07:13 AM
So I have this python script which looks roughly like this:

while 1:
proc = subprocess.Popen('sudo iwlist wlan0 scan', shell=True, stdout=subprocess.PIPE, )
results = proc.communicate()[0].split('\n')

# do stuff with wireless scan results



How would I monitor for a keypress, like the escape button, so I can exit the while loop?

mentallaxative
November 29th, 2008, 12:34 PM
You could enclose it within a try-except block, where except catches KeyboardInterrupt. The key to press will have to be Ctrl-C though.

crazyfuturamanoob
November 29th, 2008, 01:35 PM
Perhaps you could write a small C module which get's the keypresses from X11, and then sends exit signal to the python app?

I once wrote an application with C, which uses X11 to make fake key presses. Works probably the other way around too.

Majorix
November 29th, 2008, 02:10 PM
Why not use the EOF combination?

OldGregory
November 29th, 2008, 05:17 PM
You could enclose it within a try-except block, where except catches KeyboardInterrupt. The key to press will have to be Ctrl-C though.

Sounds kinda hacky...8).

That'll work fine for now, but I was just hoping there was a module I could use.

unutbu
November 29th, 2008, 08:36 PM
If you are okay with using Ctrl-C to break,
then there is the signal module which you could use to catch the SIGINT signal:


#!/usr/bin/env python
# See http://www.linuxjournal.com/article/3946 listing #3

import signal
import sys
import subprocess

def signal_handler(signal, frame):
print 'You pressed Ctrl-C!'
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print 'Press Ctrl-C to stop'
while 1:
proc = subprocess.Popen('sudo iwlist wlan0 scan', shell=True, stdout=subprocess.PIPE, )
results = proc.communicate()[0].split('\n')
# do stuff with wireless scan results