How to break a while true with keyboard interruption? - python-3.x

How can I break a while True if I press a key?, and if it is possible, how can I break a while True if a press an x key (e.g. intro)?.
while True:
if something is pressed:
print("STOP")
break
do_something()
I tryied with inputs but you can't put:
while True:
i = input() or None if program wait > 3 seconds. # > = more than
if != None:
print("STOP")
break
do_something()
Input stop all the while waiting for answer, and i don't want that.
PD: I use win 10 64-bits, python 32-bits 3.6, terminal.
PD2: Before post this question I search more about it, i found:
while True:
try:
do_something()
except KeyboardInterrupt:
pass
But this only stop with Ctrl + c, not other keys.

This only works in Windows:
import msvcrt
while True:
if msvcrt.kbhit():
break
The msvcrt provide a list of functions capables of process key inputs. msvcrt.kbhit() check if a key was pressed and it's waiting for been read and return true or false based on that.

Related

pynput.keyboard terminate program when key is pressed not responding

I have this code here and what I want is for the code to type "potato" every 5 seconds. I also want a "quit" command, and I want it so that when I press = it will stop the program. However, not only does the code not work, but it also types "=" after it types/enters "potato". Can someone help? Thanks.
from pynput.keyboard import Key, Controller
import time
keyboard = Controller()
time.sleep(3)
while True:
keyboard.type('potato')
keyboard.press(Key.enter)
keyboard.release(Key.enter)
if keyboard.type('asdf'):
quit()
time.sleep(5)
P.S. no errors or anything
The most obvious answer here would be to change the "asdf" to "=" in the if statement, but if that doesn't fix the problem, you could add a listener to detect keypresses.
from pynput import keyboard, Key, Controller
import time
# set your termination key here
cut_key = "="
# check if key pressed is cut_key, if so, quit
def on_press(key):
try:
if key.char == cut_key:
quit()
except AttributeError:
if key == cut_key:
quit()
# non-blocking listener
listener = keyboard.Listener(
on_press=on_press)
listener.start()
keyboard = Controller()
time.sleep(3)
while True:
keyboard.type('potato')
keyboard.press(Key.enter)
keyboard.release(Key.enter)
time.sleep(5)
I didn't test this code, please comment if it doesn't work.
https://pynput.readthedocs.io/en/latest/keyboard.html

Break when function run herself by console key pressing in separate thread

For example:
def main():
time.sleep(10)
pass
main()
How to break this loop by pressing 'q'?
Haven't tested it, but i think this should work.
global stop
stop = False
def main():
time.sleep(10)
if keyboard.is_pressed('q'):
global stop
stop = True
if stop:
return 0
else:
main()

msvcrt.kbhit() always returns false . Unable to detect Escape key

I tried if (msvcrt.getch() == chr(27).encode()), it didn't work
The msrcvt.getch() in my program always prints to b'\xff' in the debug-print statement.
It simply didn't detects the ESC key I am pressing. How to make it work. Please provide any sample code for Python 3.8.x.
Try: if msvcrt.getch()==b'\x1b'
Ex:
import msvcrt
while True:
if msvcrt.kbhit():
key_stroke = msvcrt.getch()
if key_stroke==b'\x1b':
print ("Esc key pressed")
else:
print (str(key_stroke).split("'")[1],"key pressed")

How to Detect 'ESC' keypress while expecting input() from user

I tried using
if msvcrt.kbhit():
key_stroke = msvcrt.getch()
if key_stroke==chr(27).encode(): #b'\x1b'
print ("Esc key pressed")
sys.exit()`
before and after the data=input('Enter a value:') but the Esc key_stroke not getting detected
That is, while expecting an input from user with input() function, if the user press Esc key, I want to do sys.exit()
Try this:
import sys
import msvcrt
def func():
print ('Enter user input:')
while True:
if msvcrt.kbhit():
key_stroke = msvcrt.getche()
if key_stroke==chr(27).encode():
print ("Esc key pressed")
sys.exit()
else:
#print (str(key_stroke).split("'")[1],"key pressed")
i=str(key_stroke).split("'")[1]+input()
print ("User input:",i)
func()
Note: I am using getche instead of getch, it is similar to getch but prints the key that is pressed.
This worked,
import msvcrt
data=input('Enter a value : ')
if(data):
print(data)
else:
print('invalid value')
key=msvcrt.getch()
if(msvcrt.getch() == chr(27).encode()):
print('Escape key pressed')
The main difference/relation between this and the said similar question is that,
The msvcrt.kbhit() couldn't be used with input() function. because it always doesn't wait for the keyboard hit. So directly using the msvcrt.getch() works perfectly.
Both the code provided for the question is mainly based on msvcrt library and that library didn't work as expected in the Python IDLE console, but perfectly in the windows command prompt
Please correct me if I am wrong

Keyboard module to return true or false statements

I am currently utilizing the pypi keyboard module and trying to return a statement of true when pressing a key while the key is pressed (e.g. "up" key), and then return false while the key is not pressed. I can initially get the program to print true or false with loops, only problem is I have to break after true or suffer infinite loop prints of true.
I would like for the program not break unless I hit the esc key.
import keyboard
x = keyboard.read_key()
while True:
try:
if x == "up":
print("True")
elif x != "up":
print("False")
except:
keyboard.wait("esc")
I was able to figure this out and I feel silly, I just wanted to ask the question to get the thought process going.
I ended up with:
import keyboard
import time
bulb = False
def LightSwitch():
global bulb
if bulb == False:
print("The light is off")
time.sleep(0.1)
bulb = True
else:
print("The light is on")
time.sleep(0.1)
bulb = False
while True:
keyboard.add_hotkey("up", LightSwitch)
keyboard.wait()

Resources