iTerm2 Python API 实战:用 setprofile 脚本把当前会话切换到指定 Profile

发布时间:2026/9/21 1:27:09
iTerm2 Python API 实战:用 setprofile 脚本把当前会话切换到指定 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 库中的 setprofile 示例文档 为骨架讲解如何编写一个完整的脚本查询全部 Profile配置档案列表按名称定位目标 Profile并将当前活动会话Session的配置切换为它。读者将掌握PartialProfile与Profile两种对象模型的使用差异、async_get_full_profile的必要性、以及会话与 Profile 分离divorced这一关键概念最终能独立编写出可复制、可运行的 iTerm2 自动化脚本。一、示例要解决什么问题在 iTerm2 中每个会话都绑定一个 ProfileProfile 决定了字体、配色、光标形状、终端类型等大量行为。日常使用中我们经常需要一键换配置比如把当前窗口从暗色主题切到亮色主题、从普通终端切到专门配置好的 SSH 终端等。手工操作需要进入Preferences → Profiles菜单层层点选而 iTerm2 提供的 Python Scripting API 允许我们用几行代码直接完成这件事。官方示例文档给出的是一个最小但完整的解决方案其核心逻辑为通过async_get_app拿到 App 对象进而访问窗口window、标签页tab与会话session的层级结构用PartialProfile.async_query高效地拉取全部 Profile 的轻量列表按名称找出目标把命中的PartialProfile升级为完整Profile交给会话的async_set_profile完成切换。二、完整示例脚本原文继承以下是官方示例文档提供的完整脚本使用 Python 3.7 语法通过 shebang 声明运行环境#!/usr/bin/env python3.7 import iterm2 async def main(connection): app await iterm2.async_get_app(connection) # Query for the list of profiles so we can search by name. This returns a # subset of the full profiles so its fast. partialProfiles await iterm2.PartialProfile.async_query(connection) # Iterate over each partial profile for partial in partialProfiles: if partial.name Default: # This is the one were looking for. Change the current sessions # profile. full await partial.async_get_full_profile() await app.current_terminal_window.current_tab.current_session.async_set_profile(full) return iterm2.run_until_complete(main)该脚本对应的 iTerm2 脚本模板.its格式可直接导入脚本管理器位于 api/library/python/iterm2/docs/examples/setprofile.its。整个脚本只有两个关键动作查 Profile与换 Profile下面逐行拆解其原理。三、逐行拆解脚本如何工作3.1 入口与事件循环run_until_complete脚本最后一行iterm2.run_until_complete(main)是 iTerm2 脚本的标准入口。它负责与正在运行的 iTerm2 应用建立 Python API 连接通过 socket / Apple Events 机制把连接对象connection注入到协程main(connection)驱动 asyncio 事件循环直到main执行完毕。所有 iTerm2 脚本都遵循这一模式定义一个接收connection的 async 函数然后交给run_until_complete执行。若想支持脚本被用户中断或接收通知事件官方还提供了run_forever等变体但本示例这种执行一次即退出的场景用run_until_complete最合适。3.2 获取应用层级async_get_appapp await iterm2.async_get_app(connection)iterm2/app.py 中的async_get_app返回一个App对象它代表整个 iTerm2 应用实例并暴露了完整的层级导航链app.current_terminal_window当前聚焦的终端窗口window.current_tab窗口当前选中的标签页tab.current_session标签页中当前活跃的会话。正是通过这条链脚本才能定位到用户当前正在看的那个会话而不需要显式地按 session_id 查找。这也是该脚本能改当前会话而非改某个固定会话的根本原因。3.3 查询 Profile 列表PartialProfile.async_querypartialProfiles await iterm2.PartialProfile.async_query(connection)这是全脚本性能设计的关键点。从 iterm2/profile.py 的源码可以看到async_query的实现如下节选staticmethod async def async_query( connection: iterm2.connection.Connection, guids: typing.Optional[typing.List[str]] None, properties: typing.List[str] [ Guid, Name]) - typing.List[PartialProfile]: Fetches a list of profiles by guid, populating the requested properties. response await iterm2.rpc.async_list_profiles( connection, guids, properties) profiles [] for response_profile in response.list_profiles_response.profiles: profile PartialProfile( None, connection, response_profile.properties) profiles.append(profile) return profiles可以提炼出三个重要信息默认只取两个属性properties默认值为[Guid, Name]。这意味着查询时只要求 iTerm2 返回每个 Profile 的全局唯一标识Guid和显示名称Name网络传输与内存开销都极小所以官方注释称之为returns a subset of the full profiles so its fast。底层走 RPC实际数据来自iterm2.rpc.async_list_profiles(connection, guids, properties)即通过 Python API 协议向 iTerm2 主程序发起ListProfiles请求。guids参数为None时返回全部 Profile。返回PartialProfile每个元素是PartialProfile对象它只包含请求到的字段name属性即为匹配目标。3.4 按名称匹配partial.nameif partial.name Default:PartialProfile继承自Profile见 iterm2/profile.py 中class PartialProfile(Profile)的定义其name属性对应 Profile 的Name键。由于async_query默认已经请求了Name这里可以安全地直接比较。如果你想改为按其他条件匹配只需把自定义的属性列表传入async_query例如# 额外请求“背景颜色”等属性用于更复杂的筛选逻辑 profiles await iterm2.PartialProfile.async_query( connection, properties[Guid, Name, Background Color])3.5 升级为完整 Profileasync_get_full_profilefull await partial.async_get_full_profile()为什么不能直接把partial传给async_set_profile原因在于PartialProfile只有查询时请求的那几个字段默认只有Guid和Name缺少async_set_profile所需写入的完整配置集合。从源码看async_get_full_profile的实现为async def async_get_full_profile(self) - Profile: Requests a full profile and returns it. Raises BadGUIDException if the Guid is not set or does not match a profile. if not self.guid: raise BadGUIDException() response await iterm2.rpc.async_list_profiles( self.connection, [self.guid], None) if len(response.list_profiles_response.profiles) ! 1: raise BadGUIDException() return Profile( None, self.connection, response.list_profiles_response.profiles[0].properties)几个关键细节它再次发起async_list_profiles但这次以[self.guid]限定只取一个 Profile且properties传None——表示请求全部属性从而得到一个字段完整的Profile对象如果guid缺失例如你构造PartialProfile时没有请求Guid属性或该 GUID 已不存在会抛出BadGUIDException。因此官方文档特别提醒如果之后要调用async_get_full_profile必须在async_query时确保请求了Guid属性返回的是真正意义上的Profile完整配置对象可作为async_set_profile的入参。3.6 执行切换async_set_profileawait app.current_terminal_window.current_tab.current_session.async_set_profile(full)iterm2/session.py 中Session.async_set_profile的定义为async def async_set_profile(self, profile: iterm2.profile.Profile): Changes this sessions profile. The profile may be an existing profile, an existing profile with modifications, or a previously unknown profile with a unique GUID. await self.async_set_profile_properties(profile.local_write_only_copy)它实际调用async_set_profile_properties并传入profile.local_write_only_copy一个只写副本见LocalWriteOnlyProfile类。文档注释还透露了一个更强大的能力传入的Profile不必是已存在的 Profile——它可以是一个修改过的现有 Profile甚至可以是一个带有全新 GUID 的前所未有的 Profile。也就是说用同样的 API 你还能实现复制一个 Profile 改几个参数后动态应用到会话而不一定非要切到列表里的某个现成配置。切换成功后会话的字体、配色等外观与行为会立即按新 Profile 生效。四、最容易踩的坑会话与 Profile 分离divorced官方文档专门用一整段强调了本示例的一个重要边界条件Note that if the session is divorced from its underlying profile (such as by making a change in theSession Edit Sessionpanel) then those changes will not be affected by this script.即如果会话已经与它的底层 Profile 分离divorced——典型场景是用户通过Session Edit Session面板做过局部修改——那么本次脚本切换不会清除这些覆盖项。原因很好理解Edit Session产生的修改被 iTerm2 记录为一份局部覆盖partial override它叠加在底层 Profile 之上。当你调用async_set_profile传入一个普通Profile时iTerm2 只会替换底层 Profile 的字段原有的局部覆盖仍然优先于是换了配置但界面没完全变。官方给出的解法是In order to override them, you should convert the partial profilepartialinto a full profile by callingawait partial.async_get_full_profile()and passing that toasync_set_profile.注意这里的措辞把查询到的partialPartialProfile通过async_get_full_profile()转成完整Profile再传入。从async_get_full_profile的源码可以看到它请求了全部属性propertiesNone返回的Profile携带该 Profile 所有字段的完整值——这实际上是一个完整快照iTerm2 在应用这种完整 Profile 时可以覆盖掉会话上的分离覆盖项。这也正是示例脚本中先async_get_full_profile再async_set_profile这一顺序的深层原因它同时保证了字段完整性与对分离会话的强覆盖能力。五、运行方式与前置条件5.1 安装 Python API 库脚本依赖iterm2库其源码位于 api/library/python/iterm2包含iterm2/包、setup.py与 README.rst。安装方式pip install iterm2要求 Python 3.7 及以上脚本 shebang 亦声明为python3.7并且本机 iTerm2 需要开启Scripting支持。5.2 两种运行方式作为独立脚本保存为.py文件后直接运行。运行前请确保 iTerm2 正在运行脚本会自动建立连接。作为 iTerm2 脚本模板使用官方提供的 setprofile.its 模板导入Scripts菜单iTerm2 菜单栏的脚本图标 → Python → New Script导入后即可从菜单中一键执行。5.3 按需修改目标 Profile示例写死匹配名为Default的 Profile。更通用的写法是把目标名称做成参数或环境变量例如import os target_name os.environ.get(TARGET_PROFILE, Default) for partial in partialProfiles: if partial.name target_name: ...六、进阶围绕 Profile 的更多 API 能力同样的对象模型还能支撑更多场景值得一并了解直接取默认 ProfilePartialProfile.async_get_default(connection)可返回当前默认 Profile 的PartialProfile见 iterm2/profile.py 中async_get_default的实现它会先通过async_get_default_profileRPC 拿到 GUID 再查询适合把会话统一切到默认配置这类需求。反向操作读取会话当前 ProfileSession.async_get_profile()iterm2/session.py返回会话当前绑定 Profile 的完整属性可用来在切换前备份、或判断会话当前处于何种配置。局部属性修改若只想改会话的个别属性而不整体切换 Profile可用Session.async_set_profile_properties只写入少数几个键开销更小。动态创建 Profile如async_set_profile文档注释所述传入带新 GUID 的Profile即可在会话上应用一个临时/私有配置适合做主题试听、对比等交互式工具。七、小结setprofile示例虽然只有三十行左右却完整展示了 iTerm2 Python Scripting 的四个核心范式用run_until_complete驱动协程入口、用async_get_app做 UI 层级导航、用PartialProfile.async_query做轻量查询、用async_get_full_profileasync_set_profile完成完整配置写入。理解PartialProfile与Profile的区别、默认只查询Guid/Name两个属性的性能取舍、以及分离会话需要完整 Profile 覆盖的边界就足以在此基础上衍生出主题切换、配置同步、一键环境切换等各类实用工具。继续深入可阅读示例原文档api/library/python/iterm2/docs/examples/setprofile.rst对象模型源码api/library/python/iterm2/iterm2/profile.pyPartialProfile、Profile、LocalWriteOnlyProfile会话 API 源码api/library/python/iterm2/iterm2/session.pyasync_set_profile、async_get_profile应用层级 APIapi/library/python/iterm2/iterm2/app.py脚本模板api/library/python/iterm2/docs/examples/setprofile.its赞分享桌面应用AI 应用【免费下载链接】iTerm2iTerm2 is a terminal emulator for Mac OS X that does amazing things.项目地址https://gitcode.com/gh_mirrors/it/iTerm2点击查看免费下载相关推荐hexo-theme-3-hexo核心功能全揭秘从分类搜索到多作者模式的终极指南hexo theme 3 hexo核心功能全揭秘从分类搜索到多作者模式的终极指南 想要打造一个极简而功能强大的Hexo博客吗hexo theme 3 hexDaft SQL 的 USE 语句详解切换当前 Catalog 与 Namespace 的会话状态管理Daft SQL 的 USE 语句详解切换当前 Catalog 与 Namespace 的会话状态管理 导读 USE 是 Daft SQL 中用于设置会话大数据数据分析数据工程AI 应用NocoBase nb env use 命令详解切换当前 CLI 环境与会话隔离机制NocoBase nb env use 命令详解切换当前 CLI 环境与会话隔离机制 nb env use 是 NocoBase CLI 中用于切换当前环境低代码后端前端人工智能AI 应用工作流自动化上一篇uni-app 跨平台图片选择指南uni.chooseImage 参数详解、相册模式与源码实现剖析下一篇PP-OCRv5_server_rec_onnx高级应用动态形状推理与多场景文本识别最佳实践创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考