gpt4 book ai didi

python - 检测特定的 Python.app 实例是否已在运行

转载 作者:行者123 更新时间:2023-12-03 17:49:45 24 4
gpt4 key购买 nike

我正在试验用 Python 编写的 OS X 应用程序,需要检测是否已经有一个使用特定脚本运行的 Python.app 实例。该脚本会即时将 CFBundleNamePython 修改为 MyApp,以更改菜单栏中的应用标题。

bundle = NSBundle.mainBundle()
info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
info['CFBundleName'] = 'MyApp'

如果我启动另一个实例并检查正在运行的应用程序的 CFBundleName,它只会告诉我原始值,即 Python:

for app in NSWorkspace.sharedWorkspace().runningApplications():
bundle = NSBundle.bundleWithURL_(app.bundleURL())
info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
name = info.get('CFBundleName')
if name in ('Python', 'MyApp'):
print name # => prints Python

因此,我需要找到一种方法来标记运行 MyApp 脚本的 Python.app 实例,以便能够中止启动重复实例。

有这样的办法吗?

更新:

在出现更好的解决方案之前,我将使用lockf

import fcntl
lockfile = open('/tmp/myapp.lock', 'w')
fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)

更新2:

好吧,我仍然需要找到我的应用程序来集中精力。目前,我只是循环遍历所有 Python.app 实例并一一聚焦它们。一般情况下只有一个,但如果很少的话就会很乱。

from Foundation import NSWorkspace
from Cocoa import NSApplicationActivateAllWindows, NSApplicationActivateIgnoringOtherApps

try:
import fcntl
lockfile = open('/tmp/myapp.lock', 'w')
fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)

except IOError as e:
assert (e.errno, e.strerror) == (35, 'Resource temporarily unavailable')

for app in NSWorkspace.sharedWorkspace().runningApplications():
if app.bundleIdentifier() == 'org.python.python':
app.activateWithOptions_(NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps)
exit()

更新3:

我将使用 pid 文件,直到出现更好的解决方案

LOCK_FILE = '/tmp/myapp.lock'
PID_FILE = '/tmp/myapp.pid'

try:
import fcntl
# NOTE: needs to be assigned to a variable for the lock to be preserved
lockfile = open(LOCK_FILE, 'w')
fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)

except IOError as e:
try:
with open(PID_FILE) as f:
pid = int(f.read())
except:
pid = None

for app in NSWorkspace.sharedWorkspace().runningApplications():
if app.bundleIdentifier() == 'org.python.python':
if not pid or pid == app.processIdentifier():
app.activateWithOptions_(NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps)
exit()

from Foundation import NSProcessInfo
info = NSProcessInfo.processInfo()
pid = info.processIdentifier()
with open(PID_FILE, 'w+') as f:
f.write(str(pid))

最佳答案

有多种方法可以解决这个问题。其中:

  • libunique - 专门为此设计的库
  • dbus - 内部通信系统

this post的答案中描述了其中的许多内容。 .

给出了独特实例的配方 here .

关于python - 检测特定的 Python.app 实例是否已在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30694560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com