繁体   English   中英

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

[英]Getting Variable from Applescript and using in Python

有没有简单的方法可以使用applescript,例如:

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

并在python中使用“ theText”变量?

您还可以使用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

有很多方法可以做到这一点。 由于它不依赖任何第三方Python模块,因此最简单的方法可能是使用OS X osascript命令行实用程序在子进程中运行脚本。 默认情况下, 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!

对于现实世界的应用程序,您可能需要进行一些错误检查和/或异常捕获。

暂无
暂无

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

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