Scanning Keypress in Python

linux, python, scripting

Solution

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

- Put the program logic code in a function, say `perform_actions`. Call it when the program starts.

- After the code has been run, start listening for an interrupt.

- That is, the user must press ctrl+c instead of ctrl+r.

- On receiving an interrupt, wait half a second; if ctrl+c is pressed again, then exit.

- 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>`.

Problem

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.

Original source

Related problems