views:

283

answers:

3

I have paused a script for lets say 3500 seconds by using time module for ex time.sleep(3500).

Now, my aim is to scan for keypresses while the script is on sleep, i mean its on this line.

Its like I want to restart the script if a "keypress Ctrl+R" is pressed.

For ex.. consider

#!/usr/bin/python
import time
print "Hello.. again"
while True:
     time.sleep(3500)

Now while the code is at last line, If i press Ctrl+R, i want to re-print "Hello.. again" line.

+3  A: 

I am aware that this does not fully answer your question, but you could do the following:

  1. Put the program logic code in a function, say perform_actions. Call it when the program starts.
  2. After the code has been run, start listening for an interrupt.
    • That is, the user must press ctrl+c instead of ctrl+r.
  3. On receiving an interrupt, wait half a second; if ctrl+c is pressed again, then exit.
  4. Otherwise, restart the code.

Thus one interrupt behaves as you want ctrl+r to behave. Two quick interrupts quit the program.

import time

def perform_actions():
    print("Hello.. again")

try:
    while True:
        perform_actions()
        try:
            while True: time.sleep(3600)
        except KeyboardInterrupt:
            time.sleep(0.5)
except KeyboardInterrupt:
    pass

A nice side-effect of using a signal (in this case SIGINT) is that you also restart the script through other means, e.g. by running kill -int <pid>.

Stephan202
A solution with ctrl+r would have been nicer ;)
tuergeist
ya.. this is also not bad. I mean it solves my problem for now. But, i wanna know how can I use this with any other combination...If anyone knows, pls continue to reply..
shadyabhi
A: 

in a for loop sleep 3500 times for 1 second checking if a key was pressed each time

ndemou
Why do i run the loop unnecessarily? How can we do it while program is in sleep state.
shadyabhi
+1  A: 

You may want to use Tkinter {needs X :(}

#!/usr/bin/env python

from Tkinter import * # needs python-tk

root = Tk()

def hello(*ignore):
    print 'Hello World'

root.bind('<Control-r>', hello)
root.mainloop() # starts an X widget

This script prints Hello World to the console if you press ctrl+r

See also Tkinter keybindings. Another solution uses GTK can be found here

tuergeist
Since Tkinker is not a standard module. I wish there was a different solution.
shadyabhi
IFAIK There is no way binding keys without using an X or widget library. So you have to use qt, gtk or tkinter :) You may want to visit http://kaizer.se/wiki/python-keybinder/ which proposes a keybinding mechanism for python. But this isn't standard python also.
tuergeist