How to Read Key pressed in python - python

How do you move a circle up, down and side to side, without downloading other things (pygame)? I tried using getch but it would not work. Can someone help me?
This is my code:
import msvcrt
key = msvcrt.getch()
while True:
print(key)

On Windows, you should use
if msvcrt.kbhit():
c = msvcrt.getch()
inside a polling loop.

You can't do anything other than installing a module. I would strongly recommend you use keyboard. Its easy to use and unlike other modules, it'll work.
Here is an example code which will detect c:
import keyboard
while True:
if keyboard.is_pressed("c"): #It will not include capital C
print("C pressed!")
break
It will receive keys from the whole Windows

Related

Why msvcrt.getch() is getting always same input without pressing any key on Windows

I am using Windows. I want take user input without pressing enter key and I found many examples, but somehow they are not working on me. I do not press any key and still msvcrt.getch() function is getting input(or atleast it is printing something) all the time. My code below:
import msvcrt
from time import sleep
while True:
print(msvcrt.getch())
sleep(1)
This is printing b'\xff' all the time. And if I press something, it does not care, it still print same string. I am using python 3.6
Problem solved. If using msvcrt: Code has to run in console. I was running that with IDLE.
https://www.reddit.com/r/learnpython/comments/3ji6ew/ordgetch_returns_255_constantly/
Thanks to ingolemo.

Python real-time keyboard input

I am not looking for input() or raw_input(). I am looking for what sounds like is available in the msvcrt module, specifically msvcrt.kbhit() and msvcrt.getch(), but am unable to get it working.
I tried example 1, here:
http://effbot.org/librarybook/msvcrt.htm
and the chosen answer here:
Python Windows `msvcrt.getch()` only detects every 3rd keypress?
both of which put me into infinite loops from which I am unable to escape by pressing 'esc' and 'q' respectively.
import msvcrt
while True:
pressedKey = msvcrt.getch()
if pressedKey == 'x':
break
I would like to avoid downloading and installing new modules, like pyhook suggested below, if possible:
How do I get realtime keyboard input in Python?
I found the answer here: Python kbhit() problems
Basically, you need to run the program from a console window instead of from the IDE (Python in my case).

Killing a Python program using ctrl C

I have an assignment in school which i can't get around and i'm stuck with.
the assignment is to build a program that infinitly spews out random numbers in a EasyGUI messagebox ( Yeah i know EasyGUI is old xD )
this is my source code:
import easygui
while True:
easygui.msgbox(random.randint(-100, 100))
The problem is that when i run this i can't get out of it. I should be allowed to use ctrl+C but that doesn't work. Am i missing something?
Thank you in advance!
your problem is that you can't use ctrl-c when using easygui, you can use ctrl-c when using the idle for example you can do
for i in range(1, 10000000000000000000000000000000000000000000000):
print(i)
that will work, it won't on easygui, since i spews out frames one by one.its to slow
using signalhandlers does not seem to be a trivial task when it comes to easygui, if you can work with quitting when x is pressed you can do the following:
while True:
e = easygui.msgbox(random.randint(-100, 100))
if e is None:
break
e will either be a string "OK" if you press ok or None if x is pressed so it is probably the simplest way to quit and end the loop.

Python - detect keypress in shell

Trying to detect and respond to key presses in Python. Am using IDLE and Python 3.3. I have the following code so far
import msvcrt
while True:
inp = ord(msvcrt.getch())
if (inp != 255):
print(inp)
I have the IF statement because if I just allow the script to throw out the value of 'inp' it just spoons out 255 repeatedly. So I threw in the if statement to respond to anything but 255 and now when run the code does nothing but output the actual keypress character in the shell.
This is because getch reads the input immediately, it doesn't wait until you type something. When it doesn't receive any input, it will simply return "\xff" (ordinal 255).
The getch function is designed to work in a console, not in a graphical program.
When you use it in a graphical program it is going to return immediately with \xff.
If you run your program in the reguler python interpreter it will not cause you that problem.
In addition, when you run the loop with the if statement it is running continuously and using a lot more processor time then it needs. In windows the only proper way of doing so is using window messages which sounds like it is overkill for your needs.
Python has a keyboard module with many features. You Can Use It In Both Shell and Console. It Also Detect Key For The Whole Windows.
Install it, perhaps with this command:
pip3 install keyboard
Then use it in code like:
import keyboard #Using module keyboard
while True: #making a loop
try: #used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('a'): #if key 'a' is pressed
print('You Pressed A Key!')
break #finishing the loop
else:
pass
except:
break #if user pressed other than the given key the loop will break
You can set it to multiple Key Detection:
if keyboard.is_pressed('a') or keyboard.is_pressed('b') or keyboard.is_pressed('c'): # and so on
#then do this
When You Install The Module, got to folder:
python36-32/Lib/site-packages/keyboard
Open File_keyboard_event.py in notepad++.
There will be keyboard events.
Not Sure About All Of Them.
Thanks.

Correct way to pause a Python program

I've been using the input function as a way to pause my scripts:
print("something")
wait = input("Press Enter to continue.")
print("something")
Is there a formal way to do this?
It seems fine to me (or raw_input() in Python 2.X). Alternatively, you could use time.sleep() if you want to pause for a certain number of seconds.
import time
print("something")
time.sleep(5.5) # Pause 5.5 seconds
print("something")
For Windows only, use:
import os
os.system("pause")
So, I found this to work very well in my coding endeavors. I simply created a function at the very beginning of my program,
def pause():
programPause = raw_input("Press the <ENTER> key to continue...")
and now I can use the pause() function whenever I need to just as if I was writing a batch file. For example, in a program such as this:
import os
import system
def pause():
programPause = raw_input("Press the <ENTER> key to continue...")
print("Think about what you ate for dinner last night...")
pause()
Now obviously this program has no objective and is just for example purposes, but you can understand precisely what I mean.
NOTE: For Python 3, you will need to use input as opposed to raw_input
I assume you want to pause without input.
Use:
time.sleep(seconds)
I have had a similar question and I was using signal:
import signal
def signal_handler(signal_number, frame):
print "Proceed ..."
signal.signal(signal.SIGINT, signal_handler)
signal.pause()
So you register a handler for the signal SIGINT and pause waiting for any signal. Now from outside your program (e.g. in bash), you can run kill -2 <python_pid>, which will send signal 2 (i.e. SIGINT) to your python program. Your program will call your registered handler and proceed running.
I use the following for Python 2 and Python 3 to pause code execution until user presses Enter
import six
if six.PY2:
raw_input("Press the <Enter> key to continue...")
else:
input("Press the <Enter> key to continue...")
print ("This is how you pause")
input()
As pointed out by mhawke and steveha's comments, the best answer to this exact question would be:
Python 3.x:
input('Press <ENTER> to continue')
Python 2.x:
raw_input('Press <ENTER> to continue')
For a long block of text, it is best to use input('Press <ENTER> to continue') (or raw_input('Press <ENTER> to continue') on
Python 2.x) to prompt the user, rather than a time delay. Fast readers
won't want to wait for a delay, slow readers might want more time on
the delay, someone might be interrupted while reading it and want a
lot more time, etc. Also, if someone uses the program a lot, he/she
may become used to how it works and not need to even read the long
text. It's just friendlier to let the user control how long the block
of text is displayed for reading.
Anecdote: There was a time where programs used "press [ANY] key to continue". This failed because people were complaining they could not find the key ANY on their keyboard :)
Very simple:
raw_input("Press Enter to continue ...")
print("Doing something...")
By this method, you can resume your program just by pressing any specified key you've specified that:
import keyboard
while True:
key = keyboard.read_key()
if key == 'space': # You can put any key you like instead of 'space'
break
The same method, but in another way:
import keyboard
while True:
if keyboard.is_pressed('space'): # The same. you can put any key you like instead of 'space'
break
Note: you can install the keyboard module simply by writing this in you shell or cmd:
pip install keyboard
cross-platform way; works everywhere
import os, sys
if sys.platform == 'win32':
os.system('pause')
else:
input('Press any key to continue...')
I work with non-programmers who like a simple solution:
import code
code.interact(banner='Paused. Press ^D (Ctrl+D) to continue.', local=globals())
This produces an interpreter that acts almost exactly like the real interpreter, including the current context, with only the output:
Paused. Press ^D (Ctrl+D) to continue.
>>>
The Python Debugger is also a good way to pause.
import pdb
pdb.set_trace() # Python 2
or
breakpoint() # Python 3
I think I like this solution:
import getpass
getpass.getpass("Press Enter to Continue")
It hides whatever the user types in, which helps clarify that input is not used here.
But be mindful on the OS X platform. It displays a key which may be confusing.
Probably the best solution would be to do something similar to the getpass module yourself, without making a read -s call. Maybe making the foreground color match the background?
user12532854 suggested using keyboard.readkey() but the it requires specific key (I tried to run it with no input args but it ended up immediately returning 'enter' instead of waiting for the keystroke).
By phrasing the question in a different way (looking for getchar() equivalent in python), I discovered readchar.readkey() does the trick after exploring readchar package prompted by this answer.
import readchar
readchar.readkey()
For cross Python 2/3 compatibility, you can use input via the six library:
import six
six.moves.input( 'Press the <ENTER> key to continue...' )
I think that the best way to stop the execution is the time.sleep() function.
If you need to suspend the execution only in certain cases you can simply implement an if statement like this:
if somethinghappen:
time.sleep(seconds)
You can leave the else branch empty.

Categories