0

I am trying to write a python3 script using pynput which presses a key in order to automate a repetitive task I have to do. The code is the following:

import time
from pynput.keyboard import Key, Controller

keyboard = Controller()

keyboard.press(Key.enter)
keyboard.release(Key.enter)
# Press and release space
while True:
    keyboard.press(Key.space)
    keyboard.release(Key.space)
    time.sleep(1)

My problem is that it works, but only in command line. I don't have any idea how to export the input to the open window with the task I have to perform. I am using an OsX system. Thank you in advance.

Hub One
  • 27
  • 8
  • Is the task part of an application? Is it a file system task? Is it reading data from a file? Can you be more descriptive about what you are trying to accomplish? All we know is the code works in console. – A Magoon Sep 29 '20 at 16:38
  • I am working on a mod of a game which is emulated in openemu and I need to press the same key for many times in an openemu window, so it is part of an application – Hub One Sep 29 '20 at 16:41

1 Answers1

0

It only works in console because the keystrokes are staying within the python environment. To interact with an application you need to use your OS. Do this in python using os.system(). Since your script is run from console you will need to first switch to your target application.

Simulate Alt+Tab:

os.system('\nosascript -e \'tell application "System Events" to key code 48 using {command down}\' \n')

You will need to add delays between your key-down and key-up commands because OpenEmu won't be able to detect key-up at the speed your script will execute.

This post has more information Macbook OpenEmu Python send keystrokes

A Magoon
  • 1,180
  • 2
  • 13
  • 21
  • I know is a stupid question, but I do not understand the ```key code 48 using {command down}``` part. I mean, why is it simulating alt+cmd? How can I simulate other key combos? – Hub One Sep 29 '20 at 19:08
  • Thank you, in general your solution is the most optimal I found, even if it turned out that OpenEmu doesn't support AppleScript, but only a quite obscure third party script language, so I had to give up. For any other tasks I think this solution is good. – Hub One Sep 29 '20 at 20:16
  • Command is Apple's version of alt. Key code 48 is for tab. My example uses python to tell the OS to switch windows. Here is a list of AppleScript keyboard commands https://eastmanreference.com/complete-list-of-applescript-key-codes Here's another helpful resource http://macbiblioblog.blogspot.com/2014/12/key-codes-for-function-and-special-keys.html – A Magoon Sep 29 '20 at 20:59