Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

python - How to programmatically open an application by name on macOS?

I'm writing a cross-platform Python application that acts as a frontend for DOSBox. It needs to call the DOSBox executable with a number of command line arguments. I don't want to hardcode a specific path to DOSBox because it might depend on where the user has installed it.

On Linux, I can simply do:

import subprocess
subprocess.run(['dosbox'] + args)

On macOS, however, I currently use the following code:

import subprocess
subprocess.run(['/Applications/dosbox.app/Contents/MacOS/DOSBox'] + args)

Which seems awfully specific and I'm not even sure whether it works, since I don't have a mac to test on.

What is the correct way to open an application by name on macOS?

(NB: I have also asked this sibling question for Windows.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't know DOSBox or want it on my Mac, but in general, when you install an application on macOS it has a "property list" file, or plist or "info.plist" in it. In there, the developer is supposed to put a "bundle identifier" key called CFBundleIdentifier. This must be unique across all applications, so for DOSBox it should be something like:

<key>CFBundleIdentifier</key>
<string>com.dosboxinc.dosbox</string>

Get one of your users to find that, then you can use the bundle identifier to open it like this regardless of installation location:

open -b BUNDLEIDENTIFIER --args arg1 arg2 arg3

where arg1, arg2 and arg3 get passed on to DOSBox.


You may be able to get the bundle identifier by running this in Terminal:

osascript -e 'id of app "DOSBox"'

Note, however, that if this command works, it means I have correctly guessed the app name "DOSBox", which means that you could just use the app name with open, rather than the bundle identifier like this:

open -a DOSBox --args arg1 arg2 arg3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...