6

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.

shadyabhi
  • 16,675
  • 26
  • 80
  • 131

3 Answers3

4

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
  • 59,965
  • 13
  • 127
  • 133
  • A solution with ctrl+r would have been nicer ;) – tuergeist Nov 19 '09 at 14:05
  • 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 Nov 19 '09 at 16:32
3

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
  • 9,171
  • 3
  • 37
  • 58
  • Since Tkinker is not a standard module. I wish there was a different solution. – shadyabhi Nov 21 '09 at 11:10
  • 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 Nov 22 '09 at 09:41
-2

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

# sleep for 3500 seconds unless ctrl+r is pressed
for i in range(3500):
    time.sleep(1)
    # check if ctrl+r is pressed
    # if pressed -> do something
    # otherwise go back to sleep
Matti Lyra
  • 12,828
  • 8
  • 49
  • 67