TRAA(To Record Anything Anywhere) 是一个跨平台的屏幕捕获库,本项目提供了其 Python 绑定,支持 Windows、macOS 和 Linux 平台。本文将详细介绍如何使用该库,以及一些技术实现细节。
在这里厚颜无耻的求一下星行不行(虽然90%以上都是用cursor生成的)?traa-py
小小的剧透 mcp-server
以下是在claude desktop中通过mcp使用该功能的截图
主要功能
- 屏幕和窗口枚举,支持多种过滤选项
- 高性能屏幕捕获
- 多显示器和窗口支持
- 缩略图和图标捕获
- 跨平台兼容(Windows、macOS、Linux)
安装使用
安装
pip install traa
or
uv add traa
基本使用
以下是一个基本的使用示例:
from traa import Size, ScreenSourceFlags, enum_screen_sources, create_snapshot
from PIL import Image
# 枚举屏幕源
sources = enum_screen_sources(
thumbnail_size=Size(160, 120), # 可选:获取缩略图
icon_size=Size(32, 32), # 可选:获取图标
external_flags=ScreenSourceFlags.NONE # 使用默认枚举行为
)
# 打印可用源
for source in sources:
print(f"找到源:{source}")
# 保存缩略图(如果有)
if source.thumbnail_data is not None:
Image.fromarray(source.thumbnail_data).save(f"thumb_{source.id}.png")
# 保存图标(如果有)
if source.icon_data is not None:
Image.fromarray(source.icon_data).save(f"icon_{source.id}.png")
# 从第一个源捕获
if sources:
# 以全高清分辨率捕获
image, actual_size = create_snapshot(sources[0].id, Size(1920, 1080))
# 根据图像形状确定模式
mode = "RGB" if len(image.shape) == 3 and image.shape[2] == 3 else \
"RGBA" if len(image.shape) == 3 and image.shape[2] == 4 else "L"
# 保存截图
Image.fromarray(image, mode=mode).save("snapshot.png")
print(f"捕获的图像大小:{actual_size}")
技术实现细节
原生模块动态库调用
TRAA Python 绑定库通过加载平台特定的动态库来实现屏幕捕获功能。不同平台的动态库存放在不同的目录中:
- Windows:
libs/windows/{arch}/traa.dll
- macOS:
libs/darwin/libtraa.dylib
- Linux:
libs/linux/{arch}/libtraa.so
这些动态库在包安装时会被自动打包到对应的 wheel 文件中。库的加载是在运行时动态完成的,具体实现采用了 Python 的 ctypes 模块。
平台特定的 Wheel 打包
为了支持不同平台和架构,项目使用了自定义的 wheel 构建类 PlatformSpecificWheel
。这个类继承自 bdist_wheel
,主要完成以下工作:
- 识别目标平台和架构:
def get_target_platform():
target = os.environ.get('TARGET_PLATFORM', '').lower()
if not target:
system = platform.system().lower()
machine = platform.machine().lower()
if system == 'windows':
target = f"windows_{'x64' if machine in ['amd64', 'x86_64'] else 'x86'}"
elif system == 'darwin':
target = f"darwin_{'arm64' if machine == 'arm64' else 'x64'}"
elif system == 'linux':
target = f"linux_{'arm64' if machine == 'aarch64' else 'x64'}"
return target
- 根据平台选择正确的动态库文件:
def get_platform_package_data(target_platform):
platform_mapping = {
'windows_x64': ['libs/windows/x64/*.dll'],
'windows_x86': ['libs/windows/x86/*.dll'],
'windows_arm64': ['libs/windows/x64/*.dll'],
'darwin_x64': ['libs/darwin/*.dylib'],
'darwin_arm64': ['libs/darwin/*.dylib'],
'linux_x64': ['libs/linux/x64/*.so'],
'linux_arm64': ['libs/linux/arm64/*.so']
}
return platform_mapping.get(target_platform, [])
- 生成平台特定的 wheel 标签:
def get_tag(self):
python_tag, abi_tag, platform_tag = super().get_tag()
platform_mapping = {
'windows_x64': 'win_amd64',
'windows_x86': 'win32',
'windows_arm64': 'win_arm64',
'darwin_x64': 'macosx_10_9_x86_64',
'darwin_arm64': 'macosx_11_0_arm64',
'linux_x64': 'manylinux2014_x86_64',
'linux_arm64': 'manylinux2014_aarch64'
}
if self.target_platform in platform_mapping:
platform_tag = platform_mapping[self.target_platform]
return python_tag, abi_tag, platform_tag
构建不同平台的 Wheel 包
要构建特定平台的 wheel 包,可以使用以下命令:
# Windows x64
TARGET_PLATFORM=windows_x64 python setup.py bdist_wheel
# macOS ARM64
TARGET_PLATFORM=darwin_arm64 python setup.py bdist_wheel
# Linux x64
TARGET_PLATFORM=linux_x64 python setup.py bdist_wheel
也可以使用项目提供的构建脚本 build_all.py
或 build_all.sh
一次性构建所有平台的 wheel 包。
注意事项
动态库依赖:确保目标系统安装了必要的系统库。在 Linux 上可能需要安装 X11 开发库。
平台兼容性:
- Windows:支持 x86、x64 和 ARM64
- macOS:支持 x64 和 ARM64 (Apple Silicon)
- Linux:支持 x64 和 ARM64
Python 版本要求:需要 Python 3.7 或更高版本。
依赖包要求:
- NumPy >= 1.16.0
- Pillow >= 8.0.0
开发环境设置:
如果要参与开发,建议安装开发依赖:pip install traa[dev]
性能优化建议
在进行屏幕捕获时,尽量指定合适的分辨率,避免不必要的缩放操作。
如果不需要缩略图或图标,在调用
enum_screen_sources
时不要指定相应的参数。使用适当的
ScreenSourceFlags
来过滤不需要的窗口,可以提高枚举性能。对于持续捕获场景,建议重用已创建的截图对象,而不是每次都创建新的。
项目配置文件说明
pyproject.toml 详解
pyproject.toml
是现代 Python 项目的标准配置文件,用于定义项目的元数据和构建要求。以下是各个字段的详细说明:
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
build-system
: 定义项目的构建系统requires
: 指定构建项目所需的依赖包build-backend
: 指定使用的构建后端,这里使用 setuptools 的构建后端
[project]
name = "traa"
version = "0.1.4"
description = "A Python library for capturing and interacting with the desktop screen"
readme = "README.md"
keywords = [
"Screen Capturer", "Snapshot", "Desktop Capturer"
]
license = { file = "LICENSE" }
authors = [
{ name = "Sylar", email = "peilinok@gmail.com" },
]
requires-python = ">=3.10"
dependencies = [
"cffi>=1.17.1",
"numpy>=2.2.3",
"pillow>=11.1.0",
]
project
: 项目的核心元数据name
: 项目名称,这将是 pip 安装时使用的包名version
: 项目版本号,遵循语义化版本规范description
: 项目的简短描述readme
: README 文件的路径,用于 PyPI 页面展示keywords
: 项目关键词,用于 PyPI 搜索license
: 项目许可证信息authors
: 项目作者信息列表requires-python
: 指定支持的 Python 版本要求dependencies
: 项目运行时依赖的包列表
[project.urls]
Homepage = "https://github.com/opentraa/traa-py"
Issues = "https://github.com/opentraa/traa-py/issues"
project.urls
: 项目相关的 URL 链接Homepage
: 项目主页地址Issues
: 项目问题追踪地址
setup.py 说明
虽然现代 Python 项目推荐使用 pyproject.toml
,但由于我们需要自定义 wheel 构建过程来支持不同平台的动态库打包,所以项目同时使用了 setup.py
。主要用途包括:
自定义 wheel 构建:
- 通过继承
bdist_wheel
类实现平台特定的 wheel 包构建 - 处理不同平台的动态库文件打包
- 生成正确的平台标签
- 通过继承
包数据管理:
package_data={ 'traa': package_data_patterns, # 动态库文件模式 }
- 确保动态库文件被正确打包到 wheel 中
- 根据目标平台选择正确的动态库文件
开发依赖管理:
extras_require={ 'dev': [ 'pytest>=6.0.0', 'pytest-cov>=2.0.0', 'black>=21.0.0', 'isort>=5.0.0', 'flake8>=3.9.0', 'wheel>=0.37.0', ], }
- 定义可选的开发依赖包
- 通过
pip install traa[dev]
安装开发所需的额外包
平台兼容性声明:
platforms=['Windows', 'Linux', 'macOS']
- 声明支持的操作系统平台
- 帮助用户了解包的兼容性范围
setup.py
和 pyproject.toml
的配合使用确保了项目既能满足现代 Python 包管理的标准,又能处理平台特定的构建需求。在实际开发中,我们主要通过 pyproject.toml
管理项目元数据和依赖,而使用 setup.py
处理特殊的构建需求。
参考资料
结语
TRAA Python 绑定库提供了一个简单而强大的接口,用于实现跨平台的屏幕捕获功能。通过合理使用其提供的 API,可以轻松实现各种屏幕录制和截图功能。如果在使用过程中遇到问题,欢迎在项目的 GitHub 仓库提出 issue。