简体   繁体   English

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

[英]Getting Variable from Applescript and using in Python

Is there any easy way to use an applescript like: 有没有简单的方法可以使用applescript,例如:

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

And use the "theText" variable in python? 并在python中使用“ theText”变量?

You can also run a python script with command line input from AppleScript: 您还可以使用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's example has python calling AppleScript, then returning control to python, this is the other way around. Ned的示例使用python调用AppleScript,然后将控制权返回给python,这是另一种方法。 Then in Python access list of parameters: 然后在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

There are a number of ways to do it. 有很多方法可以做到这一点。 Probably the simplest way, since it does not rely on any third-party Python modules, is to run the script in a child process using the OS X osascript command line utility . 由于它不依赖任何第三方Python模块,因此最简单的方法可能是使用OS X osascript命令行实用程序在子进程中运行脚本。 By default, osascript returns any output from the AppleScript execution to stdout which can be then be read in Python. 默认情况下, osascript将AppleScript执行中的所有输出返回到stdout,然后可以在Python中读取该输出。 You can try it out in the Python interactive interpreter. 您可以在Python交互式解释器中进行尝试。

With Python 3.4.1: 使用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!

With Python 2.7.7: 使用Python 2.7.7:

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

For a real world application, you'll probably want to do some error checking and/or exception catching. 对于现实世界的应用程序,您可能需要进行一些错误检查和/或异常捕获。

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

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