You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Fabric获取远程.gz文件后,Python gzip模块读取返回空字节求助

解决Fabric获取远程.gz文件后读取为空的问题

问题出在你写完BytesIO后,没有重置文件指针的位置。调用fabric_connection.get()把远程文件内容写入fd后,流的指针停在了末尾,后续用gzip.GzipFile读取时,从这个位置开始读自然只能得到空字节。

修改代码,在get操作后加上fd.seek(0),把指针移回流的起始位置即可:

try:
    fabric_connection = Connection(host=host_name, connect_kwargs={'key_filename': tmp_id, 'timeout': 10})
    
    fd = io.BytesIO()
    remote_file = '/home/test/test.txt.gz'
    fabric_connection.get(remote_file, fd)
    # 重置BytesIO的指针到起始位置
    fd.seek(0)

    with gzip.GzipFile(mode='rb', fileobj=fd) as fin:
        content = fin.read()
        print(content)
        decoded_content = content.decode()
        print(decoded_content)

except BaseException as err:
    assert not err

finally:
    fabric_connection.close()

简单解释下:BytesIO作为内存流,写入数据后指针会自动移动到最后,就像你打开本地文件写完内容后直接读,也会读不到东西一样。用seek(0)把指针移到开头,gzip就能正确读取整个压缩文件的内容了。

内容的提问来源于stack exchange,提问作者kadina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 21:05:11