Home > Blockchain >  Simple use of Python’s Subprocess.call to open multiple Mac apps
Simple use of Python’s Subprocess.call to open multiple Mac apps

Time:10-25

I’d like to open a few apps using a very simple python script:

from subprocess import call
call("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
call("/Applications/MongoDB Compass.app/Contents/MacOS/MongoDB Compass")

The problem is that opening them this way seems to open a terminal window along with the app itself - for chrome, it outputs this in the terminal for example:

Last login: Sun Oct 23 00:20:38 on ttys000
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome ; exit;
nick@Nicks-MBP ~ % /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome ; exit;
objc[3817]: Class WebSwapCGLLayer is implemented in both /System/Library/Frameworks/WebKit.framework/Versions/A/Frameworks/WebCore.framework/Versions/A/Frameworks/libANGLE-shared.dylib (0x7ffb45565ec8) and /Applications/Google Chrome.app/Contents/Frameworks/Google Chrome Framework.framework/Versions/106.0.5249.119/Libraries/libGLESv2.dylib (0x116ba9668). One of the two will be used. Which one is undefined.

So it hijacks the terminal and does not proceed to this next line:

call("/Applications/MongoDB Compass.app/Contents/MacOS/MongoDB Compass")

If I try to call these:

call(("/Applications/Google Chrome.app"))
call(("/Applications/MongoDB Compass.app"))

I get this error, with other posts stating that it may be a dir and not an app:

OSError: [Errno 13] Permission denied

How can this be fixed? Note that I do not want to do this despite it working:

os.system("open /Applications/"   app   ".app")

Because I need to be able to wait for the apps to finish opening before running another command, hence the use of Subprocess.call. Thank you.

UPDATE:

I now have this:

print("start")
call(
    [("/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome")],
    shell=True,
    stdout=subprocess.DEVNULL,
    stderr=subprocess.STDOUT,
)
print("end")

But the print("end") line only executes when I exit out of chrome. How can I get it to wait for Chrome to load and then print 'end' after? Also it requires Shell=True for some reason, otherwise it complains with:

FileNotFoundError: [Errno 2] No such file or directory: '/Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome

CodePudding user response:

Updated Answer

This also appears to work and doesn't involve the shell:

import subprocess as sp
print("start")
sp.run(["open", "-a", "Google Chrome"])
print("end")

Original Answer

This appears to do what you want, though I have no explanation as to why:

import subprocess as sp

print("start")
sp.Popen(
   ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"],
   stdin =sp.DEVNULL,
   stdout=sp.DEVNULL,
   stderr=sp.DEVNULL)
print("end")
  • Related