Python script that runs in commandline detects keypress everywhere - python-3.x

currently im Working on a small project for myself and im detecting keypresses in my script but it also detects them while im typing for example in a game
if keyboard.is_pressed("q"):
sys.exit()
how can I prevent it from doing it and only detect when i have the cmd open

The purpose of Keyboard library is to hook global key presses, i.e., out of focus as they said in their docs.
Don't do this! The keyboard module is meant for global events,
even when your program is not in focus.
To get the keys when the window is focused, you can try the below solutions.
Solution 1:
You can use getkey library. You have to install it with pip.
pip install getkey
And implement it like this:
from getkey import getkey
while True:
key = getkey()
print(key)
if key == "q":
break
Solution 2:
If you are a Windows user, you can use getch() in msvcrt module like this:
import msvcrt
while True:
if msvcrt.kbhit():
key = msvcrt.getch()
print("Key Pressed", key)
if key == "q":
break

Related

Is there a way to get all keyboard input from turtle in python not just specific keys

Is there a way to get all keyboard input from turtle in python not just specific keys. I am aware I can use turtle.onkey(up, "Up") to call a function on a specific key press but I want to be able to get any key press without having to go through and manually set a function for every single key as I want to be able to display user text input in the turtle window directly without having to use console or alternatives like that.
the answer is no, you can't do it only with turtle, turtle built with tkinter and tkinter don't have that option, if you want to do it you should import other modules like pyinput, but pyinput may not that easy to learn (I didn't really try)
I just use the module "keyboard" (to download it on windows go to command prompt and type pip install keyboard) but I didn't try all of the functions with that module and I don't know if it is fully trusted, I just use it for one simple function which is
from keyboard import is_pressed as pressed
if keyboard.pressed('h'): # just for example it should be a string
# what ever you want to do here
so I really recommended to just learn pyinput cause it is really has more options, but if you don't use a lot of options you can do like me.

disable failSafeCheck Python PyAutoGui without editing the pyautogui file

So I'm using PyCharm as a python editor, and I don't know if it's because of my editor, but whenever I run a simple PyAutoGui program such as:
import time, pyautogui
time.sleep(3)
while True:
pyautogui.hotkey('ctrl', 'r')
time.sleep(15)
for too long, I keep getting an error (I don't have that error currently, because I usually have to wait a long time before getting the error from pyautogui. But it looks something like) :
PyAutoGUI fail-safe triggered from mouse moving to a corner of the screen.
I'm not very experienced with Python PyAutoGui module, but is there a way to disable that safe-check without doing something in the pyautogui python file?
You're in luck! Just add pyautogui.FAILSAFE = True right after importing the library.
Check out their docs it has a lot of good info.

How can I get a real-time input via keyboard module?

import keyboard
def printPressedKey(e):
print("key pressed : {}".format(e.name))
keyboard.hook(printPressedKey)
keyboard.wait('esc')
this code prints pressed keys when I press esc. I want to print pressed keys as I press keys. How can I do this?
EDIT
This happens only when you execute python via nppexec in notepad++ so you just execute it on the console. Sorry for everyone ;(
Use pyinput package, it works well for both mouse and keyboard
https://pypi.org/project/pynput/

pynput keyboard listener does not detect keys on Mac OS X

I am using pynput to record keystrokes via Listener on OS X Mojave. I am using Pycharm as my IDE for running the code.
I was not able to get it to work using the same example from the pynput site.
from pynput.keyboard import Listener as key_listener
class recorder:
def on_press(self, key):
print(key)
def on_release(self, key):
print(key)
if __name__ == "__main__":
testme = recorder()
with key_listener(on_press=testme.on_press, on_release=testme.on_release) as listener:
listener.join()
I did step through it and I get no errors (unless I put the with statement in a function, instead of in the main, but that's a known issue with threading in Mojave, from what I can tell after searching for that error), but everything stops at the .join() statement, and I get nothing printed when I press and release a key on my keyboard.
This is probably a bit late, but the answer is to go into:
Settings -> Security & Privacy
Click on the Privacy tab
Click the + Hold down CMD + SHIFT + . (so that you can see hidden
files/folders)
Navigate to /usr/local/bin or wherever you have Python installed
Click okay.
That should do it.
Note
If you try to run your app via the terminal, you will need to add the terminal.app to the list of allowed apps, as done above for Python.
Found the problem.
For some strange reasons; OSX is uber-picky about returning events, so unless you go in the security settings and enable Pycharm to be in the list of apps that are allowed to use accessibility, it won't work.
I didn't try on Windows yet, but I assume it will be the same issue. The only gripe I have is that I have no idea how to add Python itself to the list of supported accessibility apps; since the control panel does not allow me to go in /usr/local/bin, which is where I have Python3 installed (via Brew).
This is probably a bit late too, but the simple answer is to go into:
Preference
Security & Privacy
Input Monitoring
-> confirm PyCharm
Some people have stated that adding IDLE to supported accessibility apps is what allows python itself to run the listener.
while your in a finder window, if you press cmd+shft+'.' (period key) it will show hidden files, which will allow you to navigate to usr/local/bin and look for your python implementation.
On windows this is slightly different, I always run python/pycharm as admin and it never gives me any issues.
Try superuser ($sudo su) and run your python code in terminal, I think
it should work
Im was working with OSX 10.12 and pynput was only getting cmd ctrl fn and option keys when pressed but now in superuser it gets the keys.

"Press enter to exit" does not work

I have started to read the book Python for absolute beginners (3rd edition) by Michael Dawson.
And one of the first challenges in the book is to run a programme the author wrote to see what it does.
That is what it looks like:
# Game Over
# Demonstrates the print function
print("Game Over")
input("\n\nPress the enter key to exit.")
When I then continue to run the module the following comes up.
"> RESTART: some of my information
Game Over
Press the enter key to exit."
However, when I press enter, the programme does not quit, like he said it would do in the book. He says, the window would disappear, which it does not.
What is wrong with my computer? I have a MacBook, am however using the newest python software from the website.
If you could help me, I would be very grateful, as I am just starting out and am a little wondered what is wrong with my stuff.
Thank you
Answer based on comment of OP:
When I then hit enter the following comes: ">>>" with every tap on
enter a new line with those three characters appears. The problem
still does not close though
So, after pressing enter, you see
>>>
and if you press enter again, you see
>>>
>>>
The "program" (which is the python script) is actually closed, and you have exited. The >>> you see is the python prompt.
To exit the python prompt, type exit() and press enter
I think this will work
First, install keyboard package using this code
pip install keyboard
Second, Use this code
import keyboard
# Game Over
# Demonstrates the print function
print("Game Over\n\nPress the enter key to exit.")
while True:
if keyboard.is_pressed("enter"):
exit(0)

Resources