Python Forum
Opening and closing Mac applications and files - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Opening and closing Mac applications and files (/thread-29478.html)



Opening and closing Mac applications and files - Nickd12 - Sep-04-2020

So I've been trying to open and close Mac OS. applications and files with python but have had little to no success can anyone provide me with any clue on how to do this.

For example one would be open Mac OS. calendar


RE: Opening and closing Mac applications and files - bowlofred - Sep-04-2020

If you want to launch an app and wait for the user to exit, you could use /usr/bin/open and subprocess.run. If you want to continue the program after launching, could use subprocess.Popen.

>>> import subprocess
>>> subprocess.run(["/usr/bin/open", "-a", "calendar"])  # waits until calendar exit
CompletedProcess(args=['/usr/bin/open', '-a', 'calendar'], returncode=0)
>>> subprocess.Popen(["/usr/bin/open", "-a", "calendar"]) # returns immediately
<subprocess.Popen object at 0x1065e3048> 
I'm not sure if there's a more direct interface that avoids /usr/bin/open.


RE: Opening and closing Mac applications and files - Nickd12 - Sep-04-2020

is there an argument that I could make to close the calendar app as well not have the user close it


RE: Opening and closing Mac applications and files - bowlofred - Sep-04-2020

Maybe, but not through this method. I'm not an apple developer, so I don't know what's common for them, but there appears to be a javascript interface to some applications.
Javascript for automation

I don't know how well that works, and I don't know if there's any similar python interface to that kit. Hopefully someone else around here will be more familiar with it.


RE: Opening and closing Mac applications and files - Nickd12 - Sep-04-2020

would it be the same way to open a file and would there be a way to close a file


RE: Opening and closing Mac applications and files - perfringo - Sep-05-2020

To close app from terminal in MacOS one can use AppleScript or pkill:

osascript -e 'quit app "Calendar"'

pkill -x Calendar