问题
When I start an app with subprocess.Popen on Mac OS X, it starts in the background and you have to click the icon in the dock to bring it to the front. How can I make it start in the foreground?
I have tried using "open", but that creates and unwanted terminal window.
Note: the app is being started from a GUI app written using wxPython.
回答1:
I think you will need to use the native API and some python bindings.
NSRunningApplication and it's method activateWithOptions is what you need. Here is an example how to use it: How to launch application and bring it to front using Cocoa api?
Look at PyObjC for bindings.
from Foundation import *
from Cocoa import *
import objc
pid = 1456
x = NSRunningApplication.runningApplicationWithProcessIdentifier_(pid)
x.activateWithOptions_(NSApplicationActivateAllWindows)
Update:
The following line is more aggressive in activating the app.
x.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)
Also you might need to .unhide()
the app first.
x.hide()
x.unhide()
回答2:
Snies' answer worked for me. However, since you only need NSRunningApplication and NSApplicationActivateIgnoringOtherApps, you might as well not import everything else. The following worked for me and was considerably faster:
from Cocoa import NSRunningApplication, NSApplicationActivateIgnoringOtherApps
pid = 1456
x = NSRunningApplication.runningApplicationWithProcessIdentifier_(pid)
x.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)
来源:https://stackoverflow.com/questions/10655484/how-to-start-an-app-in-the-foreground-on-mac-os-x-with-python