Can Python be used to dispatch true keystroke events on Mac

My question is, is there a way to reliably hold a key on mac using applescript / python?

I have a search almost everywhere on such topics, but not one of them has cut it. I am trying to use Python to read sequential information from Arduino, and then relay these signals as keystrokes. I saw how to use applescript to send a "key down" to a system event, as shown in the following code:

(Python code) def SendDown(key): string = str(key) cmd = """osascript -e 'tell application "System Events" to key down (key code """ + string + ")'" os.system(cmd) 

This code works as a whole, however I want to control the Google flight simulator. When I try to do this, the keystrokes seem to be quick, and the flight simulator or google earth basemap moves a fraction of what I expect.

I use this code mainly as follows (suedocode)

 if (ArduinoMessage == "left"): SendDown(leftKey) #leftKey has been set to 123 -- the code for the left arrow key etc... 

From my point of view, the down event that I am sending is essentially a quick keystroke, and the key is not held. I tried programming the key event directly in applescript and had a bit of success. My code looked something like this:

 tell application "System Events" repeat 50 times key down (key code 123) end repeat key up (key code 123) end tell 

This code moved the Google Earth map more than I received, but it took a long time to get it to move a small amount (much less than the usual arrow keys). Then I tried to write this applescript in Python and lost all the improvements.

So, I repeat the question - is there a way to reliably hold a key on mac using applescript / python?

I managed to get this to work on Windows quite easily, but I was able to use only the Windows library called SendKeys, designed for such applications.

Any help would be appreciated.

Thanks,

Jake

+6
source share
1 answer

Use PyUserInput . Try the following code.

 import time import pykeyboard # TODO: Replace following two lines with the code that activate the application. print('Activate the application 3 seconds.') time.sleep(3) k = pykeyboard.PyKeyboard() k.press_key(k.left_key) time.sleep(1) # Hold down left key for 1 second. k.release_key(k.left_key) 

Sorry, I don't have a Mac. I tested on Linux, Windows.

+2
source

Source: https://habr.com/ru/post/948993/


All Articles