iTerm2 最新测试版 3.3.0 加了个 Python API,可以用 Python 控制 iTerm2,之前只能用 AppleScript。
虽然看不懂 async
/ await
,照着例子写了个从 Emacs 发送命令到 iTerm2 的功能,原来的 AppleScript 也能做到,所以没有新意。估计优点在于 Python >> AppleScript 吧。
#!/usr/bin/env python3.7
import sys
import iterm2
# This script was created with the "basic" environment which does not support adding dependencies
# with pip.
async def main(connection):
app = await iterm2.async_get_app(connection)
session = app.current_terminal_window.current_tab.current_session
await session.async_send_text(sys.stdin.read())
iterm2.run_until_complete(main)
(defun chunyang-send-region-to-iterm (b e)
"Send the text of the current region to iTerm2."
(interactive "r")
(let ((python (expand-file-name "~/Library/ApplicationSupport/iTerm2/iterm2env/versions/3.7.2/bin/python"))
(script (expand-file-name "~/Library/ApplicationSupport/iTerm2/Scripts/test.py")))
(call-process-region b e python nil nil nil script)))
顺便一提,call-process-region
除了接受 Region,也能接受字符串,比如让 iTerm2 切换到 Emacs 的当前目录:
(chunyang-send-region-to-iterm (format "cd %s\n" default-directory) nil)