[英]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.