I am searching for any module for OSX automation like opening any app via Python and controlling mouse, keyboard via Python etc. I tried with AppleScript but I was wondering if I can access mouse, keyboard and can automate any app on OSX using Python? I found pyauto
, If there is any other good Python library, module for OSX automation please let me know.

- 3
- 2

- 12,007
- 7
- 50
- 88
-
ATOMac / pyatom is the only one in Python so far. It works on Python2.7 only, but good enough to get texts etc. – Vasily Ryabov Oct 05 '17 at 05:23
1 Answers
I too am looking for a good python module to use 'applescript' within python. In fact this is how I got here. I was unable to find anything so I had to come up with my own solution.
What works well for me is to call osascript from within my python programme using the subprocess module.
More precisely, (see the code below for an example), if I want to add something to my calendar I generate the applescript that does it as string in my python programme and then pipe it into osascript.
This is not super elegant and probably also not super fast but it works well. So, I am currently writing a calendar module that has python functions for adding events, getting list of events .... and each generates the applescript as string and calls osascript.
It sounds terrible but works quite well and once you have a module for your favourite programme you don't need to worry anymore about applescript.
One needs a way to encode in the applescript the return data and then decode it in the python programme. As for me most data passed to and from the applescript are dictionary-like, this has not been an issue so far using the re module.
Here is an example to get the uid of the calendar "Birthdays".
The main problem with my method is that I need to write wrapper functions for everything I want to access in applescript. A tiresome process.
The main advantage I see is a) it works and I get where I want and b) it seems future proof. For, if apple at some point discards applescript in favour of javascript or whatever, then all my programmes will still work once I adapted the wrapper modules.
Anyway ...
Hope that helps.
By the way, if anyone knows of a better way let me know. Or if someone does not know of a better way but likes my approach and would be interested in helping writing wrapper modules, let me know as well.
Here is the example.
Best, Stephan
import subprocess
def asrun(ascript):
"Run the AppleScript ascript and return the standard output and error."
return subprocess.run(['osascript'],
input=ascript,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8")
def get_uid_of_calendar(name):
script = '''\
tell application "Calendar"
return uid of calendar "'''+name+'''"
end tell
'''
cal_res = asrun(script)
return cal_res.stdout
get_uid_of_calendar("Birthdays")

- 26
- 2