python - 如何从 Python 中的 AppleScript 获取返回值?
问题描述
我需要在 Python 中获取窗口的大小并将其分配给变量。我正在尝试这个:
windowSize = '''
tell application "System Events" to tell application process "%(app)s"
get size of window 1
end tell
''' % {'app': app} // app = "Terminal
(wSize, error) = Popen(['osascript', '/Setup.scpt'], stdout=PIPE).communicate()
print("Window size is: " + wSize)
我只收到此错误:TypeError: can only concatenate str (not "bytes") to str
我对 Python 完全陌生,所以我希望你能帮助我
解决方案
您需要将 AppleScript(即windowSize
)作为输入传递给Popen.communicate()
:
例子:
from subprocess import Popen, PIPE
app = "Terminal"
windowSize = '''
tell application "%(app)s"
get size of window 1
end tell
''' % {'app': app}
proc = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)
wSize, error = proc.communicate(windowSize)
print("Window size is: " + wSize)
备注:
在你的
windowSize
AppleScript 中它不应该是必要的tell application "System Events" to tell ...
- 你可以tell application "%(app)s"
代替。但是,假设在“系统偏好设置”中启用了对辅助设备的访问,您的 AppleScript 仍然有效。这将在控制台中记录如下内容:
Window size is: 487, 338
您可能需要考虑
str.replace()
在print
语句中使用 . 替换逗号 (,
)x
。例如,将print
上述要点中的语句更改为:print("Window size is: " + wSize.replace(",", " x"))
将打印这样的东西:
Window size is: 487 x 338
如果您想用一行(类似于您的 OP)替换上面 gist 中以
proc
and开头的两行代码,wSize
然后将它们替换为以下内容:(wSize, error) = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True).communicate(windowSize)
要将窗口宽度和高度作为两个单独的变量,您可以随后使用该
str.split()
方法拆分wSize
变量(使用字符串", "
作为分隔符)。例如:# ... wWidth = wSize.split(", ")[0] wHeight = wSize.split(", ")[1] print("Window width is: " + wWidth) print("Window height is: " + wHeight)
推荐阅读
- ios - 在 AVAssetExportSession 中链接多个 CAAnimation
- django - 如何合并两个 Django 查询但保留结果?
- cassandra - 如何设计 NoSQL 数据库按时间戳选择数据顺序
- python - “Dropout”、“Monte-Carlo Dropout”和“Channel-wise Dropout”有什么区别?
- python - 如何解决“ValueError:支持的目标类型是:('binary','multiclass')。得到了'multiclass-multioutput'。” pyton 3.7 中的错误
- c# - 如何异步等待任务完成
- typescript - 请求 http.put 不要执行
- reactjs - 如何在 react-image-lightbox 中设置图像样式?
- vue.js - 如何动态绑定到组件内的对象属性?
- android - 更改 sharedPreferences 名称后无法获取数据