Keypress Scanning in Python

I paused the script, letting it say 3500 seconds using the time module for ex time.sleep (3500).

Now my goal is to scan keystrokes while the script is in sleep mode, I mean it in this line.

As if I want to restart the script if the "Ctrl + R" key is pressed .

For ex .. consider

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

Now that the code is on the last line, if I press Ctrl + R, I want to print the line "Hello .. again" again.

+5
source share
3 answers

I know this does not fully answer your question, but you can do the following:

  • , perform_actions. , .
  • interrupt.
    • ctrl + c ctrl + r.
  • ; ctrl + c , .
  • .

, , ctrl + r. .

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

( SIGINT) , script , . kill -int <pid>.

+4

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

script Hello World , ctrl+r

. Tkinter keybindings. , GTK,

+3

during a sleep cycle 3,500 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
-2
source

All Articles