How to start an app in the foreground on Mac OS X with Python?

前提是你 提交于 2020-01-14 22:49:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!