用 iTerm2 Python API 从 Emacs 给 iTerm2 发送命令

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)
3 个赞

棒极了,applescript 实在是写得难受

async 和 await是Python3.5.2引入的两个关于协程的关键字。替换了以前的增加async def表示协程函数,await替换了以前的yield from 形式

一直在等这个,结果系统版本太低不支持。看来必须得升级了,不然很多软件无法安装。

async await这不是照抄js的么:joy::joy::joy:

Python 的 async/await (PEP 492) 始于 3.5 ( Release Date: Sept. 13, 2015) Python Release Python 3.5.0 | Python.org

JS 的 async/await 始于 ES 2017 (was finalized in June 2017) ECMAScript - Wikipedia

5 个赞