Reputation: 121
So basically I need a Python program or a module that only executes the main program once a specific key is pressed, for example the F10 key. All the other modules I found (for example getch) executes once any key it pressed.
Upvotes: 0
Views: 130
Reputation: 7616
Since you mention msvcrt
, I'll assume that (Windows). You'd do it different in Linux.
F10
is a 2-byte return, 00 68
, so... you look for the first byte 00
, then the second byte 68
. There is also a 2-byte return that has a 224
for the first byte, so you'll want to check for that, too.
I included a block on kbhit()
because if you let it block on getch()
instead, it will pick up a Ctrl-C
and you won't be able to break out. Blocking on this gives you that opportunity.
You can make this a little more generic if you'd like, this is hardcoded for F10
.
import msvcrt
while True:
if msvcrt.kbhit():
first = ord(msvcrt.getch())
if first in (0, 224):
second = ord(msvcrt.getch())
if first == 0 and second == 68:
break
Upvotes: 1
Reputation: 10173
If you are already using getch
, you might as well loop over it and wait for your key:
while getch() != 'MAGIC KEY':
pass
This will forever run getch
, until the user presses the key you want. Then the flow continues as normal.
Upvotes: 0