I have a relatively simple script and a potentially simple question. Around the internet I've gathered a few solutions on how to use direct key press' as input in my python code. I'd prefer these to raw_input as it feels faster. Like if I have a menu with 3 options, and 3 options in each of those, I can easily press 3 then 2 on my keyboard to get where I need to go.
The code is:
import keyboard
import time
def mainmenu():
while(True):
print ('1. Scan')
print ('2. Ping')
print ('3. Exit')
if keyboard.is_pressed('1'):
print ('Option 1\n')
elif keyboard.is_pressed('2'):
print ('Option 2\n')
elif keyboard.is_pressed('3'):
print ('Exiting\n')
exit(0)
else:
print ('none of the specified options were chosen')
time.sleep(0.3)
exit(0)
mainmenu()
I just want something that will pause the code where I can press a key.
I can't use time.sleep() for some reason. It doesn't like inputs in the split second before or after it either.
It would be awesome if I could get a function to do it so I could input it elsewhere along the way.
If I didn't have my else statement at the end, the while loop just keeps going.
If I don't have it in a while loop the script prints the options in 1 second and then defaults to else, because I haven't pressed a key in the 1 second.
I know it works because if I take out the else statement and while its spamming the options over and over I press 3, IDLE asks if I'd like to kill the script while its running.