【问题标题】:Using Applescript to fire python script使用 Applescript 触发 python 脚本
【发布时间】:2019-09-17 00:51:28
【问题描述】:

我正在尝试使用 Applescript 来触发 python 脚本。当我从终端启动它时,一切正常,但是当我从 Applescript 启动它时,它似乎运行但没有任何反应。

对于在搜索和其他帖子中使用“python file.py”或“/usr/bin/python file.py”和“#!/usr/bin/”可以找到的所有内容,我已经尝试了各种组合方式env python”和“#!/usr/bin/python”。
如果我在终端输入“which python”,我会得到“/usr/bin/python”

现在我将两个脚本分解为它们的基本组件。我最终将使用 Applescript 使用 sys.argv[1] 将文件路径传递给 python(这就是我使用 Applescript 来触发 python 脚本的原因)但我还没有那么远,因为下面没有还没用。

苹果脚本

do shell script "/usr/bin/python $HOME/Desktop/test.py"

Python

#!/usr/bin/python

import sys
import os

# The notifier function
def notify(title, subtitle, message):
    t = '-title {!r}'.format(title)
    s = '-subtitle {!r}'.format(subtitle)
    m = '-message {!r}'.format(message)
    os.system('terminal-notifier {}'.format(' '.join([m, t, s])))

# Calling the function
notify(title    = 'Message Test',
       subtitle = 'Test1:',
       message  = 'Test2')

sys.exit(0)

python 脚本发送通知消息。每次我在终端运行时,我都会收到没有问题的消息。每次我运行 applescript 以作为 shell 脚本执行时,它在 AS 中运行时不会出错,但没有来自 Python 的消息。

有人知道我哪里出错了吗?

【问题讨论】:

  • 我在我的 Mac 上重新创建了你的 Python 代码和 AppleScript 并且它可以工作(在我用终端通知器注释掉该行之后(因为我没有安装它)并用一个简单的替换打印)。当我在存在终端通知程序的情况下运行它时,Python 中出现错误,但 AppleScript 中没有。我相信 AppleScript 只能返回由您调用的代码发送到标准输出的输出。也许终端通知程序不打印任何内容,添加打印语句可能会帮助您了解正在发生的事情......

标签: python applescript


【解决方案1】:

如果您使用二进制文件的完整路径,它对您有用吗?它在 BBEdit 和 Smile(脚本编辑器)中都对我有用。我的路径是:

/Applications/terminal-notifier-2.0.0/terminal-notifier.app/Contents/MacOS/terminal-notifier

所以我用了:

#!/usr/bin/python

import sys
import os

# The notifier function
def notify(title, subtitle, message):
    t = '-title {!r}'.format(title)
    s = '-subtitle {!r}'.format(subtitle)
    m = '-message {!r}'.format(message)
    os.system('/Applications/terminal-notifier-2.0.0/terminal-notifier.app/Contents/MacOS/terminal-notifier {}'.format(' '.join([m, t, s])))

# Calling the function
notify(title    = 'Message Test',
       subtitle = 'Test1:',
       message  = 'Test2')

sys.exit(0)

【讨论】:

    猜你喜欢
    • 2011-10-10
    • 2018-09-05
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    相关资源
    最近更新 更多