Pynput: input out of command line

823 Views Asked by At

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.

1

There are 1 best solutions below

3
On BEST ANSWER

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