Python: detect keyboard before other processes - python

I wrote a Python script that performs simple actions based on what I press on my keyboard.
The script always works perfectly, except when Visual Studio Code is open and active.
It's like VSCode is catching the pressed keys BEFORE my python script.
If I close VSCode, or just minimize the window, and another window is active, my python script works again.
VSCode does not "steal" the keys only from python scripts, it steals them from other applications as well. For example, when VSCode window is active, I can not use my OBS shortcut for start recording.
I tried to lower VSCode priority and increase my python script priority, but it did not work.
Does anyone know how can I make my python script catch the pressed keys, before VSCode steals them?
EDIT:
Please find below a minimum reproducible example.
The following script prints an a when the a key is pressed on the keyboard. It works with any active window, except VSCode. In fact, when VSCode window is active it stops working.
Tests done in Windows 10.
from keyboard import is_pressed
from time import sleep
while True:
if is_pressed('a'):
print('a')
sleep(0.2)

I have found the solution!
I noticed that my VSCode was set to always run as administrator. I set this option months ago, and somehow persisted even after completely uninstalling and reinstalling VSCode.
I just disabled the option and now it works!
Thank you ColdFish and MingJie for all of your help.

Thanks for the detail Jeffrey. I could not reproduce the issue on a reasonably fresh install of VSCode, also on Windows 10.
I looked through the documentation in the readme of the keyboard package and found this in the "Known Limitations" section:
Other applications, such as some games, may register hooks that swallow all key events. In this case keyboard will be unable to report events.
I'm going to hazard a guess that one of your VSCode plugins is registering a hook to capture key events. I suspect that if you try it on a fresh VSCode installation (which will be similar to mine) it may work.
Alternatively, you can try using another similar implementation in pynput of the same functionality. That may work without any alterations to VSCode. A minimum example is here that will mirror the functionality of your minimum example:
from pynput.keyboard import Key, Listener, KeyCode
def on_press(key):
if key == KeyCode.from_char('a'):
print('{0} pressed'.format(key))
while True:
with Listener(on_press=on_press) as listener:
listener.join()
You can find further documentation on how to handle the keyboard with pynput here.

Related

Having a problem with pyautogui and some programs

I ran into a problem using pyautogui with one program. I've used it successfully in the past and this had me stumped for a while. The mouse would not click on a button, or anywhere over the running programs window. I searched but could not find a solution. PyDirectInput would not work either.
I considered using Autohotkey as a workaround but it had the same problem.
The Fix:
I found the solution when searching why Autohotkey would not work. It turned out that the program I was trying to control was running in elevated mode and I needed to run my Python program as Administrator in order to interact with it.
The answer was to run my program as Administrator when trying to interact with a program running in elevated mode (also running as Administrator).

How can I make an auto clicker with pyautogui only when I activate it

I have been wanting to make this for a while and have finally gotten around to it. But could not get it to work. I need it to be able to work on macOS Linux and windows, I also need it to be able to be deactivated and activated with the press of a button.
This is what I have tried.
`
import pyautogui
import time
while True:
cookie = pyautogui.locate("cookie.png")
pyautogui.click("cookie.png")
`
First, you should check if "cookie.png" looks the same in macOS, Linux and Windows. If it does not then you may need two or three different .png
Second, the code is quite ok. If you want to stop the clicking then you can use the library keyboard (better than pyautogui for keyboard control). Then you can define the keyword to stop the clicking.

Working on an auto clicker with python and I can't open the file

Every time I open the file through file explorer it immediately closes. I'm working on it through VS code and it runs fine through there but when I double click the file (.py) it opens the closes. I've tried making it into an exe (to give to my friend) through pyinstaller and without a -w it still closes and with a -w it says "Fatal error detected, Failed to execute script AutoClicker". I tried -w to see if the program would stay open but I assume that it closes because there is nothing to show.
import mouse
import keyboard
while True:
if keyboard.is_pressed(','):
mouse.click('left')
if keyboard.is_pressed('.'):
break
You should try structuring your loop like this:
while True:
if keyboard.is_pressed(','):
mouse.click('left')
elif keyboard.is_pressed('.'):
break
elif ...
And run your code from the terminal, if you are on Windows press Win+R, type cmd and go to the directory where your file resides (cd <directory name>). Then you can open the file with Python by typing python <filename>. If you see any errors, you should probably pip install the keyboard and mouse packages you are trying to import.
Try using the pyautogui (and keyboard) module, as shown below:
from keyboard import is_pressed as isp
from pyautogui import click
from time import sleep
def clicky(click_key='.', stop_key='F10'):
while not isp(stop_key): # Execute till the stop key is pressed
if isp(click_key): # If click key is pressed,
# Click the left button two times with a 0.2 second delay between clicks
click(button='left', clicks=2, interval=0.2)
sleep(0.5) # Wait .5 seconds before checking again
clicky() # Run the function
The above code works perfectly on my Windows PC. If it does not work for you, try using the pydirectinput module, it's an updated version of pyautogui (With almost the same functions - check the link). Quoting from the PyPI page:
PyAutoGUI uses Virtual Key Codes (VKs) and the deprecated mouse_event() and keybd_event() win32 functions. You may find that PyAutoGUI does not work in some applications, particularly in video games and other software that rely on DirectX. If you find yourself in that situation, give this library a try!

Pyautogui click() and moveTo() not working mac os bigsur

I've been trying to use the pyautogui library but when i try to use the move() the python launcher bounces on the dock then disappears and nothing happens, i don't even get any errors, I saw a post from a while back when catalina was around and the person who made the post ended up going back to an older OS X because they couldn't figure out a solution, i also found the problem on the github repo for pyautogui but the solution which was to add your terminal or python launcher or code editor to accessibility list in privacy didn't work for me. Below i'm providing my code, the github issue link and the other person's post, by the way i've done everything they said they've done. I'd really appreciate some help, thanks.
Is anyone else having PyAutoGUI issues after updating to Catalina?
pyautogui.click() almost seems to work. Clicks work in the window that
I tell it to, but it's as if immediately after a click, the window
focus returns to VS Code or Terminal. And then any
pyautogui.typewrite, keyup, keydown, any of those keystroke commands
are entered into VS Code or Terminal rather than the window I've had
it click on to focus. Doing a command + tab doesn't do the trick
either as those keys are entered into Terminal rather than acting as
hotkeys on OSX. I can't seem to keep the focus on the window I'm
trying to operate on. I've tried reverting from zsh back to bash. I've
tried adding Terminal, zsh, bash, and VS Code in the Accessibility
area of Security & Settings to give full keyboard and mouse control.
Apple does say that their depreciating Quartz (what pyautogui is built
off of to operate OSX) in 10.15 (realized this one too little, too
late). But that's supposed to mean it still works they just won't be
updating it, right? Anyone else experiencing this? I'm hoping for
someone smarter than me who can guide me to a fix. Thanks!
import os, sys, subprocess
import pyautogui
import time
def open_file(filename):
if sys.platform == "win32":
os.startfile(filename)
else:
opener = "open" if sys.platform == "darwin" else "xdg-open"
subprocess.call([opener, filename])
def runZoom():
open_file("/Applications/zoom.us.app")
joinbtn=pyautogui.locateCenterOnScreen("Join_Meeting.png", confidence=.5)
pyautogui.moveTo(joinbtn)
pyautogui.click()
runZoom()
Github issue link:https://github.com/asweigart/pyautogui/issues/247
Try to use PyDirectInput module.
pip install pydirectinput
I was having trouble until I enabled access to accessibility features, thanks!
I also ran into this issue on my mac, you have to manually add Python Launcher to the list of apps that can control your computer.
System preferences --> Security & Privacy --> Accessibilty --> +Python Launcher
i also added terminal to the list.

Python Keyboard shortcuts

So, I have a python script running I the background, and I want it to trigger X function whenever a key combination is pressed. How would I implement that? The problem is that the app will be running in the background, so it won't have focus from the OS.
Well, it basicly has nothing to do with python. That heavily depends on the operating system you're working on.
You can use XLib under Linux (http://python-xlib.sourceforge.net/) or wxPython under Windows (http://wxpython.org/docs/api/wx.Window-class.html#RegisterHotKey)
Another idea would be to hook the system keyboard events (through pyHook) and try to catch any hotkeys.

Categories

Resources