2

My issue is rather simple. I want to run a loop while the user holds down a key, in my case R.

The catch is: I don't want to use PyGame, and the console window will not be focused. (Selected)

Edit: I saw that this question was labeled a duplicate. I have checked the other thread, and the key difference between the two is that this one needs to check for a key to be held, with the python/console window out of focus and not selected.

Jacob Birkett
  • 1,927
  • 3
  • 24
  • 49
  • Sounds like you need some thread to listen for keyboard input... What have you tried to achieve this? – OneCricketeer Jul 17 '16 at 17:32
  • @cricket_007 I don't know what to try, everything I found on Google was for PyGame. **Edit:** And you would need to tell me how to use multithreading, since nobody seems to be able to help me with that. – Jacob Birkett Jul 17 '16 at 17:34
  • 2
    Duplicate? http://stackoverflow.com/questions/11918999/key-listeners-in-python – OneCricketeer Jul 17 '16 at 17:37
  • @cricket_007 Apologies if it is a duplicate, didn't see that. – Jacob Birkett Jul 17 '16 at 17:38
  • I think it's only in a terminal, though... If you are using Windows, I would suggest AutoHotKey – OneCricketeer Jul 17 '16 at 17:39
  • @cricket_007 I just looked that up, its nothing like what I want. Maybe a link to what your talking about, so I could find the right one? – Jacob Birkett Jul 17 '16 at 17:41
  • I'm sure you found the correct link. It's not python, but you could execute a python script in the while loop. Here's a forum post. https://autohotkey.com/board/topic/59307-how-to-make-a-key-press-repeatedly-while-its-down/ – OneCricketeer Jul 17 '16 at 17:45
  • Might want to look at PyQt, QKeyPress event. I've never tried to do this though. – Rick Jul 17 '16 at 17:47

1 Answers1

0

In case you are using windows:

msvcrt is probably the library you are looking for (https://docs.python.org/2/library/msvcrt.html). This lib contains the kbhit function, which 'Return true if a keypress is waiting to be read':

from msvcrt import kbhit, getch

while (kbhit()):
    getch()
    #code

The getch reads the key, so it doesn't stay in the loop forever (because the kbhit function still detects a non-read key).

  • Thanks! One slight problem: It cant detect key press if the console window is out of focus. ```while True: if kbhit() and getch() == b'r':``` – Jacob Birkett Jul 18 '16 at 00:17