十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

iTerm2 Python API 实战:用脚本把会话字体一键放大 6 磅(RPC + 会话级 Profile 修改)

iTerm2 Python API 实战:用脚本把会话字体一键放大 6 磅(RPC + 会话级 Profile 修改) 桌面应用AI 应用【免费下载链接】iTerm2iTerm2 is a terminal emulator for Mac OS X that does amazing things.项目地址https://gitcode.com/gh_mirrors/it/iTerm2点击查看免费下载本篇文章以 iTerm2 官方 Python API 示例increase_font_size为骨架完整讲解如何编写一个通过按键触发的脚本将当前会话的字体放大 6 磅同时不修改底层 Profile。读完本文你将掌握 iTerm2 Python 脚本中「字体字符串解析」「会话级 Profile 覆盖LocalWriteOnlyProfile」「RPC 注册」与「按键绑定」四件套的完整实战姿势并能在仓库源码层面理解其底层实现。一、这个示例教会你什么官方示例increase_font_size位于仓库 api/library/python/iterm2/docs/examples/increase_font_size.rst是一个麻雀虽小五脏俱全的经典示例。它演示了三条核心技术能力改变单个会话的 Profile 而不触碰底层 Profile——这是 iTerm2 脚本里最常用也最容易踩坑的场景很多临时性调整放大字体、换配色、改标题都不应该污染全局配置解析并修改字体设置——iTerm2 中字体以「名称 空格 字号」的字符串形式存储脚本用正则完成拆解与重组注册一个 RPC——把 Python 协程暴露给 iTerm2 调用随后可以像绑定系统快捷键一样把它绑到任意按键上。示例完成后你可以在Prefs Keys中新增一个按键绑定动作选择Invoke Script Function调用名填写increase_font_size(session_id: id)之后每次按下该按键当前活动会话的字体就会放大 6 磅。二、完整脚本与逐行拆解官方示例的完整代码如下来自 increase_font_size.rst#!/usr/bin/env python3.7 import iterm2 import re async def main(connection): app await iterm2.async_get_app(connection) # This regex splits the font into its name and size. Fonts always end with # their size in points, preceded by a space. r re.compile(r^([^ ]* )(\d*)(.*)$) iterm2.RPC async def increase_font_size(session_id): session app.get_session_by_id(session_id) if not session: return # Get the sessions profile because we need to know its font. profile await session.async_get_profile() # Extract the name and point size of the font using a regex. font profile.normal_font match r.search(font) if not match: return groups match.groups() name groups[0] size int(groups[1]) remainder groups[2] # Prepare an update to the profile that increases the font size # by 6 points. replacement name str(size 6) remainder change iterm2.LocalWriteOnlyProfile() change.set_normal_font(replacement) # Update the sessions copy of its profile without updating the # underlying profile. await session.async_set_profile_properties(change) await increase_font_size.async_register(connection) iterm2.run_forever(main)1. 脚本入口iterm2.run_forever(main)run_forever是 iTerm2 脚本的标准启动方式。它的签名位于 connection.py接收一个async def协程函数该函数接收一个Connection参数连接建立后即运行并且函数永不返回——这正是 RPC 脚本的典型形态脚本需要保持常驻等待 iTerm2 在任意时刻发起调用。def run_forever(coro, retryFalse, debugFalse) - None: try: Connection().run_forever(coro, retry, debug) except (ConnectionRefusedError) as exception: sys.exit(1)需要注意RPC 处理函数必须注册后保持进程存活因此这里用run_forever而非run_until_complete后者在协程返回后即退出。若希望脚本在 iTerm2 尚未运行时反复尝试连接可以传入retryTrue。2. 获取应用对象与目标会话app await iterm2.async_get_app(connection)async_get_app定义于 app.py返回一个App对象它是整个 iTerm2 窗口/标签/会话对象图的根。在 RPC 回调内部session app.get_session_by_id(session_id) if not session: returnget_session_by_id定义于 app.py。注意 RPC 的参数名session_id与调用签名increase_font_size(session_id: id)中的id类型是一一对应的iTerm2 会把「当前活动会话」的 session id 传给这个参数。回调里先做空值防御如果会话不存在直接返回避免脚本在会话关闭等竞态条件下抛异常。3. 读取会话 Profileasync_get_profile()profile await session.async_get_profile()async_get_profile定义于 session.py它向 iTerm2 发起get_profileRPC 请求返回一个Profile对象。关键语义在注释里写得很清楚Fetches the profile of this sessionincluding any session-local changes not in the underlying profile.也就是说它拿到的是该会话的完整生效配置含会话级覆盖这正是脚本后续「在现有字体基础上 6」的前提——必须先知道当前字体是多少磅。4. 用正则拆分字体字符串r re.compile(r^([^ ]* )(\d*)(.*)$) font profile.normal_font match r.search(font)iTerm2 的字体字符串格式是「字体名 空格 字号 后缀」。例如Menlo Regular 12或带风格修饰的字体名。正则拆成三组分组含义示例Menlo Regular 12([^ ]* )字体名含末尾空格Menlo Regular(\d*)字号磅值12(.*)剩余后缀通常为空注意正则第一组用了[^ ]*非空格字符 一个空格因为字体名内部可以含空格如Menlo Regular只有最后一个空格是名字与字号的分隔符。若匹配失败字体格式异常则直接return安全退出。5. 构造新字体并放大 6 磅name groups[0] size int(groups[1]) remainder groups[2] replacement name str(size 6) remainder将字号部分转成整数加 6再与原名字、后缀拼接回字符串。这里「6」就是示例标题里 Increase Font Size By 6 的含义你可以随意改成其他增量比如size 2。6. 会话级 Profile 修改LocalWriteOnlyProfilechange iterm2.LocalWriteOnlyProfile() change.set_normal_font(replacement) await session.async_set_profile_properties(change)这是全示例的灵魂所在。LocalWriteOnlyProfile定义于 profile.py其类注释点明了设计意图A profile that can be modified but not read and does not send changes on each write. UseSession.async_set_profile_propertiesto update a session without modifying the underlying profile.它内部维护一个values字典键是 Profile 属性的显示名值是 JSON 序列化后的数据所有set_xxx方法都经由_simple_set把值做json.dumps后存入。本例调用的set_normal_font定义于 profile.pydef set_normal_font(self, value: str): Sets the normal font. ... The value is a fonts name and size as a string. return self._simple_set(Normal Font, value)其语义是只写入Normal Font这一项改动而不是替换整个 Profile。async_set_profile_properties定义于 session.py源码明确承诺When you use this function the underlying profile is not modified. The session will keep a copy of its profile with these modifications.底层会遍历write_only_profile.values将每对(key, json_value)作为ProfileProperty通过async_set_profile_properties_json发给 iTerm2rpc.py在支持批量写入的版本走单次请求旧版本3.3.0beta9 及更早则退化为逐属性写入。响应非 OK 时抛出RPCException。对比如果你改用session.async_set_profile(profile)session.py传入的 Profile 会被整体切换甚至可以是全新的 GUID Profile而LocalWriteOnlyProfileasync_set_profile_properties是「只改几个字段、其余全部保持现状」的精确手术刀。放大字号这类临时性操作绝不应该改动用户的全局 Profile 文件这正是本示例要传达的最佳实践。7. RPC 注册iterm2.RPC与async_registeriterm2.RPC async def increase_font_size(session_id): ... await increase_font_size.async_register(connection)iterm2.RPC装饰器定义于 registration.py它把一个协程变成「可被 iTerm2 调用的远程函数」。装饰器为被装饰函数附加async_register协程调用它完成注册。源码中明确了 RPC 签名的规则Every RPC must have a unique signature. The signature is composed of two parts: first, the name, which comes from the name of the coroutine being decorated; second, the names of its arguments. The order of arguments is not important.也就是说唯一标识 函数名 参数名集合参数顺序无关紧要。这是按键绑定时填写调用签名的基础。当 iTerm2 触发该 RPC 时消息由generic_handle_rpcregistration.py分发它把每个参数的json_value反序列化后按名传入协程执行完成后把返回值或异常栈回传给 iTerm2。所以session_id参数会收到 iTerm2 传来的会话 ID来自按键时的活动会话。三、按键绑定把函数绑到快捷键上脚本以run_forever常驻并注册好 RPC 后就可以在 iTerm2 的图形界面里绑定快捷键了官方文档给出的步骤为打开Prefs Keys点击新增一个按键绑定Action选择Invoke Script FunctionInvocation填入increase_font_size(session_id: id)session_id: id是 iTerm2 提供的参数占位符id表示「当前活动会话的 session id」iTerm2 会在触发时自动注入。由于 RPC 签名只关心「参数名」只要参数名保持session_id顺序或写法按上述规范即可被正确匹配。绑定完成后在任何会话中按下该快捷键就会观察到字体即时放大 6 磅而Profile 配置面板Prefs Profiles中的字体没有任何变化——这正是会话级覆盖生效的直接证据。四、运行方式与下载运行前提需要 Python 3.7 环境与iterm2Python 包仓库内的 Python API 库源码位于 api/library/python/iterm2/iterm2/并在 iTerm2 的Scripts菜单中启用脚本支持。脚本建议通过 iTerm2 的脚本管理机制如 Scripts 目录或 Python API 的安装流程安装为可执行脚本以#!/usr/bin/env python3.7shebang 方式运行。下载源文件官方为每个示例提供了打包好的.its脚本文件本示例对应仓库中的 increase_font_size.its即原文档底部:Download:指令指向的文件可直接导入使用。五、扩展与变体理解了核心机制后可以轻松改出更多实用变体改为减小字号把size 6换成size - 6并注意在size小于等于增量时做下界保护例如max(size - 6, 6)改用非 ASCII 字体LocalWriteOnlyProfile还提供set_non_ascii_fontprofile.py逻辑与set_normal_font完全对称可用于「启用 Non-ASCII Font 时的独立字体」场景放大后再缩小切换宏注册两个 RPC如increase_font_size/decrease_font_size分别绑到不同快捷键形成字体缩放组合键会话范围更广的操作同一套「LocalWriteOnlyProfileasync_set_profile_properties」模式还被官方其他示例复用例如copycolor、settabcolor等见 profile.py 的 seealso 交叉引用可以把「只改当前会话、不动全局」的原则推广到颜色、标题、光标等其他 Profile 属性上。六、小结这个不足 40 行的示例浓缩了 iTerm2 自动化中三个高频知识点知识点核心 API源码位置会话级 Profile 修改LocalWriteOnlyProfileasync_set_profile_propertiesprofile.py、session.py字体属性读写Profile.normal_font/set_normal_fontprofile.pyRPC 注册iterm2.RPCasync_registerregistration.py掌握「会话级覆盖」与「RPC 按键触发」的组合拳你就可以为 iTerm2 打造出大量不影响全局配置的轻量级快捷工具——字号缩放只是起点。赞分享桌面应用AI 应用【免费下载链接】iTerm2iTerm2 is a terminal emulator for Mac OS X that does amazing things.项目地址https://gitcode.com/gh_mirrors/it/iTerm2点击查看免费下载相关推荐Genkit Python Agent 会话与会话持久化Session Store实战指南Genkit Python Agent 会话与会话持久化Session Store实战指南 导读 本文围绕 Genkit PythonBetaAgentAI 技能人工智能大模型使用 iTerm2 Python API 一键清除会话缓冲从全部标签页到当前标签页的完整实现使用 iTerm2 Python API 一键清除会话缓冲从全部标签页到当前标签页的完整实现 本技术指南讲解如何借助 iTerm2 官方 Python 绑定桌面应用AI 应用cli-anything-iterm2 Session Control 完全指南基于 iTerm2 Python API 的会话生命周期管理cli anything iterm2 Session Control 完全指南基于 iTerm2 Python API 的会话生命周期管理 导读 本文面向使人工智能AI AgentAI 技能工具调用CLI上一篇告别断网焦虑Electron应用离线功能开发指南下一篇oh-my-openagent 数据工程实战Polars DuckDB 混合引擎数据处理指南创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表