The blessed Python library looks great for making console apps, but I'm having trouble with the keyboard functionality. In the code below, only every second keypress is detected. Why is this please?
I'm on Windows 10 with Python 3.8.
from blessed import Terminal
term = Terminal()
print(f"{term.home}{term.black_on_skyblue}{term.clear}")
with term.cbreak(), term.hidden_cursor():
while term.inkey() != 'q':
inp = term.inkey()
if inp.name == "KEY_LEFT":
print("You pressed left")
Move term.inkey() outside your inner while loop instead so it listens for keys first:
from blessed import Terminal
term = Terminal()
print(f"{term.home}{term.black_on_skyblue}{term.clear}")
with term.cbreak(), term.hidden_cursor():
inp = term.inkey()
while term.inkey() != 'q':
if inp.name == "KEY_LEFT":
print("You pressed left")
Related
Hello everyone im fairly new to python and this is my first language im learning so far. Im making a menu using a while true loop that takes input to select whichever flashing method a person needs to use and after calling whatever file using subprocess.popen or subprocess.call and it finishes it goes back into the menu loop but does not respond to any input at all.
import sys
import time
import subprocess
#!/bin/bash
sys.path.append
menu = True
def mainMenu():
while menu:
print("""
##################
# Utilities Menu #
##################
1. Tray Flasher
2. ESP Burner
3. Quit
""")
choice = (input('Select a utility: '))
if choice == '1':
trayFlasher()
elif choice == '2':
espBurner()
elif choice == '3':
print('Goodbye!')
def trayFlasher():
print('Have Fun!')
time.sleep(1)
subprocess.call(["<path to file>"])
def espBurner():
print('Burn Baby Burn...')
time.sleep(1)
subprocess.Popen(['<path to file>'])
sorry if my code is not so good or efficient, currently still learning. TIA!
I am currently making a python project in curses, I want to know how to use the control and shift keys using stdscr.getch(), the other keys work, except for a few keys including ctrl and shift.
The code for the files look like this
# script_1.py
import curses
stdscr = curses.initscr()
curses.noecho()
curses.curs_set(False)
curses.start_color()
stdscr.keypad(True)
curses.mousemask(True)
# script_2.py
from script_1 import *
cmd = stdscr.getch()
if cmd == curses.KEY_CONTROL_L:
print("You pressed Left Control") # This code won't work
elif cmd == curses.KEY_SHIFT_L:
print("You pressed Left Shift") # This code won't work
I am a c++ User and im am newly learning python,
i used to use getch() statements in c++ to get user input without having to press enter although it had some limitation ... I am looking for a similar function in python (anything other than raw_input() & input() which require enter key stroke). would prefer the code to have cross platform support
for eg in c++ :
void getkey()
{
_getch();
cout<<"You Hit A Key";
}
Here is a simple example using keyboard:
import keyboard
while True:
event = keyboard.read_event()
if event.event_type == keyboard.KEY_DOWN:
key = event.name
print(f'Pressed: {key}')
if key == 'q':
break
You could do this if you are on a windows OS.
import msvcrt
print("Press y or n to continue: \n")
getLetter = msvcrt.getch()
if getLetter.upper() == 'S':
print("cool it works...")
else:
print("no it doesn't work...")
Was writing a simple drum machine on a Raspberry Pi using Python and Sonic Pi: press a key, play a sound. Here's the core of the input routine.
pip install getch
import getch
while True:
key = getch.getch()
if key == 'x':
break
I am making a snake game which requires the player to press the WASD keys without stopping the game process to to get input from player. So I can't use input() for this situation because then the game stops ticking to get input.
I found a getch() function which immediately gives input without pressing enter, but this function also stops game ticking to get input like input(). I decided to use threading module to get input via getch() in different thread. The problem is that getch() isn't working while in different thread and I'm not sure why.
import threading, time
from msvcrt import getch
key = "lol" #it never changes because getch() in thread1 is useless
def thread1():
while True:
key = getch() #this simply is almost ignored by interpreter, the only thing it
#gives is that delays print() unless you press any key
print("this is thread1()")
threading.Thread(target = thread1).start()
while True:
time.sleep(1)
print(key)
So why getch() is useless when it is in thread1()?
The problem was that you're creating a local variable key inside thread1 instead of overwriting the existing one. The quick-and-easy solution would be to declare key to be global inside thread1.
Finally, you should consider using locks. I don't know if it's necessary or not, but I'd imagine weird things could happen if you try and write a value to key in the thread while printing it out at the same time.
The working code:
import threading, time
from msvcrt import getch
key = "lol"
def thread1():
global key
lock = threading.Lock()
while True:
with lock:
key = getch()
threading.Thread(target = thread1).start()
while True:
time.sleep(1)
print(key)
I tried using getch but it didn't work for me... (win7 here).
You can try using tkinter module // but I still can't make it running with threads
# Respond to a key without the need to press enter
import tkinter as tk #on python 2.x use "import Tkinter as tk"
def keypress(event):
if event.keysym == 'Escape':
root.destroy()
x = event.char
if x == "w":
print ("W pressed")
elif x == "a":
print ("A pressed")
elif x == "s":
print ("S pressed")
elif x == "d":
print ("D pressed")
else:
print (x)
root = tk.Tk()
print ("Press a key (Escape key to exit):")
root.bind_all('<Key>', keypress)
# don't show the tk window
root.withdraw()
root.mainloop()
As Michael0x2a says you may try using library made for game-making - pygame or pyglet.
#EDIT #Michael0x2a:
Are you sure your code works?
Whatever I press it always prints the same key.
#EDIT2:
Thanks!
I was wondering how do I get a key pressed in python
I tried doing:
import msvcrt as keys
while True:
key = keys.getch()
if key == "a":
print("You have pressed a")
Does anyone know how to fix it?
This might help you:
import msvcrt
while True:
if msvcrt.kbhit() and msvcrt.getch() == chr(97): # chr(97) = 'a'
print("You have pressed a")
Note: your code and my code won't work in many Python IDE's! You need to execute the python file, e.g. in a command window.