繁体   English   中英

Python 和 Applescript 使用部分应用程序名称运行应用程序的路径?

[英]Python and Applescript path of running application using a partial app name?

我正在编写一个 Python 程序(试图坚持包含的模块),并且需要仅使用部分应用程序名称来获取在 MacOS 平台上打开/活动的应用程序的路径。 (例如,使用“Adobe Acrobat Reader DC”中的“Acrobat”)。 在标准输出中获取路径 output 的正确 applescript 代码是什么? (如果 MacOS 上有更好的方法,请告诉我)。 (注意:在我的情况下需要是 subprocess.run 而不是 subprocess.Popen )

import subprocess

def get_window_path():
    cmd = """
        tell application "System Events",
          if (get name of every application process) contains "Acrobat" then
            return POSIX path of (path to ((get name of every application process) contains "Acrobat"))
          end if
        end tell
    """
    result = subprocess.run(['osascript', '-e', cmd], capture_output=True)
    return result.stdout

print(get_window_path())

不知道从python调用AppleScript ,但是......

以下示例AppleScript代码假定您只有一个名称中包含“Acrobat”的应用程序正在运行,否则您需要在repeat循环中处理从系统事件返回的列表

tell application "System Events" to ¬
    set appAcrobatList to the ¬
        name of every application process ¬
        whose background only is false ¬
        and name contains "Acrobat"

if appAcrobatList is not {} then ¬
    return POSIX path of ¬
        (path to application ¬
            (first item of appAcrobatList))

下面的AppleScript解决方案将在应用程序运行时返回应用程序的路径。 如果有多个,它还将返回应用程序所有正在运行的实例的路径(无需repeat循环)。

property singleAppPath : missing value
property multipleAppPaths : missing value

tell application "System Events"
    set searchedApps to a reference to ¬
        ((every application process) whose name contains "Acrobat" or ¬
            displayed name contains "Acrobat")
    if (count of searchedApps) is 1 then
        set singleAppPath to POSIX path of application file of searchedApps as text
    else if (count of searchedApps) > 1 then
        set multipleAppPaths to POSIX path of application file of searchedApps
    end if
end tell

Instead of switching back and forth between Python and AppleScript, another option would be to keep everything in Python and use the built-in PyObjC bridge to access the Cocoa API. AppleScript 可以很好地完成它的工作,但在这种情况下,您实际上并不需要使用它。

我在 Python 方面并不是那么出色,但以下使用NSWorkspaceNSPredicate过滤器(使用标准 Catalina 和 Big Sur 安装进行测试 - 请注意 Apple 使用旧版本):

#!/usr/bin/env python

from Cocoa import NSWorkspace, NSPredicate

appName = "Acrobat"
runningApps = NSWorkspace.sharedWorkspace().runningApplications()
predicate = NSPredicate.predicateWithFormat_("localizedName contains[c] '%s'" % appName)
results = runningApps.filteredArrayUsingPredicate_(predicate)

if results == []:
   print("Matching Application Not Found")
else:  # just get some values from the first match
   print(results[0].localizedName())
   print(results[0].bundleIdentifier())
   print(results[0].bundleURL().path())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM