从AppleScript获取变量并在Python中使用

0 投票
2 回答
1415 浏览
提问于 2025-04-18 11:17

有没有什么简单的方法可以使用像这样的苹果脚本:

set theText to text returned of (display dialog "Please insert Text here:" default answer "" with title "exchange to python" with icon 1)

然后在Python中使用“theText”这个变量呢?

2 个回答

0

有很多方法可以做到这一点。最简单的方法可能是使用 OS X 的 osascript 命令行工具,因为它不需要任何第三方的 Python 模块。默认情况下,osascript 会把执行 AppleScript 的输出返回到标准输出(stdout),这样你就可以在 Python 中读取这些输出。你可以在 Python 的交互式解释器中试试看。

如果你使用的是 Python 3.4.1:

>>> import subprocess
>>> theText = subprocess.check_output(['osascript', '-e', \
       r'''set theText to text returned of (display dialog "Please insert Text here:" default answer "" with title "exchange to python" with icon 1)'''])
>>> theText
b'Hell\xc3\xb6 W\xc3\xb2rld!\n'
>>> print(theText.decode('UTF-8'))
Hellö Wòrld!

如果你使用的是 Python 2.7.7:

>>> theText
'Hell\xc3\xb6 W\xc3\xb2rld!\n'
>>> print(theText.decode('UTF-8'))
Hellö Wòrld!

在实际应用中,你可能还需要做一些错误检查和异常捕获。

1

你还可以通过AppleScript来运行一个带有命令行输入的Python脚本:

--make sure to escape properly if needed
set pythonvar to "whatever"
set outputvar to (do shell script "python '/path/to/script' '" & pythonvar & "'")

Ned的例子是Python调用AppleScript,然后再把控制权交回给Python,而这里是反过来的做法。在Python中可以访问参数列表:

import sys
var_from_as = sys.argv[1] # for 1rst parameter cause argv[0] is file name
print 'this gets returned to AppleScript' # this gets set to outputvar

撰写回答