如何使用Python读取GCP存储桶中的bag文件并转换后上传至其他存储桶
解决方案
方案1:本地临时文件中转(兼容性最好)
该方案适配所有大小的bag文件,ros相关库原生支持读取本地文件,无需额外做流适配,是优先选择的方案。
依赖安装命令:pip install google-cloud-storage rosbags
参考代码:
from google.cloud import storage import tempfile import os from rosbags.rosbag1 import Reader from rosbags.serde import deserialize_cdr # 初始化GCP存储客户端 storage_client = storage.Client() # 源bucket和bag文件路径配置 src_bucket_name = "替换为源bucket名称" src_blob_name = "替换为bag文件在bucket内的路径" bucket = storage_client.bucket(src_bucket_name) blob = bucket.blob(src_blob_name) # 下载bag到临时文件 with tempfile.NamedTemporaryFile(suffix='.bag', delete=False) as tmp_file: blob.download_to_file(tmp_file) tmp_path = tmp_file.name try: # 读取bag并处理的业务逻辑 with Reader(tmp_path) as reader: for connection, timestamp, rawdata in reader.messages(): # 按需求做消息转换 msg = deserialize_cdr(rawdata, connection.msgtype) # 后续处理逻辑... finally: # 处理完成删除临时文件释放磁盘空间 os.unlink(tmp_path) # 处理结果上传到目标bucket dest_bucket_name = "替换为目标bucket名称" dest_blob_name = "替换为处理后文件的存储路径" dest_bucket = storage_client.bucket(dest_bucket_name) dest_blob = dest_bucket.blob(dest_blob_name) # 这里的processed_file_path替换为你处理后生成的本地文件路径 dest_blob.upload_from_filename(processed_file_path)
注意事项:
- 在GCP内部服务(云函数、Cloud Run、GCE)运行时,给服务账号配置对应存储桶的读写权限即可;本地运行需要提前配置
GOOGLE_APPLICATION_CREDENTIALS环境变量指向服务账号密钥文件。 - 大文件下载时可以设置
blob.chunk_size = 10 * 1024 * 1024开启分块下载,避免超时。
方案2:内存流式读取(适合1G以下的小型bag文件)
不需要写入本地磁盘,直接将bag文件加载到内存处理,运行速度更快,但内存占用与bag文件大小一致,大文件禁止使用。
参考代码:
from google.cloud import storage from io import BytesIO from rosbags.rosbag1 import Reader storage_client = storage.Client() src_bucket = storage_client.bucket("替换为源bucket名称") blob = src_bucket.blob("替换为bag文件路径") # 直接将bag读取到内存 bag_content = BytesIO(blob.download_as_bytes()) with Reader(bag_content) as reader: for connection, timestamp, rawdata in reader.messages(): # 转换处理逻辑 pass
常见问题排查
- 权限报错:检查运行脚本的身份是否有源存储桶的
storage.objects.get权限、目标存储桶的storage.objects.create权限。 - bag文件读取失败:优先使用
rosbags库,纯Python实现无需安装完整ROS环境,同时支持ROS1和ROS2的bag格式;旧的rosbag库依赖ROS运行环境,非ROS机器很难配置。
内容的提问来源于stack exchange,提问作者Dudes
相关产品推荐
相关产品推荐

