Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanning Keypress in Python

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.

like image 823
Abhijeet Rastogi Avatar asked Nov 19 '09 11:11

Abhijeet Rastogi


People also ask

How do you check if any key is pressed in Python?

Using pynput to detect if a specific key pressed In this method, we will use pynput Python module to detecting any key press. “pynput. keyboard” contains classes for controlling and monitoring the keyboard.

How do you wait for key press in Python?

In Python 2 use raw_input(): raw_input("Press Enter to continue...") This only waits for the user to press enter though. This should wait for a keypress.

How do I know which key I pressed?

The Windows on-screen keyboard is a program included in Windows that shows an on-screen keyboard to test modifier keys and other special keys. For example, when pressing the Alt , Ctrl , or Shift key, the On-Screen Keyboard highlights the keys as pressed.


1 Answers

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

like image 161
Stephan202 Avatar answered Oct 26 '22 11:10

Stephan202