将tarfile读入BytesIO

cyb*_*ron 7 python byte tar

我正在使用Docker-py API来处理和操作Docker容器.在该函数中API,put_archive()函数期望该data字段以字节为单位.所以,使用tarfile我有的库:

import tarfile
import io

container = client.create_container(image="myimage", command="/bin/bash")
source = "~/.ssh/id_rsa.pub"
tarfile = create_tar_file(path=source, name="keys.tar")
# tarfile = "keys.tar"
# How can I read the tar file was a BytesIO() object?
data = io.BytesIO()
client.put_archive(container=container, path="/tmp", data=data)
Run Code Online (Sandbox Code Playgroud)

API说:

put_archive(container,path,data)

    使用tar存档作为源在现有容器中插入文件或文件夹.

    参数:

        container(str) - 将提取文件的容器.
        path(str) - 将提取文件的容器内的路径.必须存在.
        data(bytes) - 要提取的tar数据

    返回:True如果调用成功.

    返回类型:(布尔)

    提升:docker.errors.APIError- 如果服务器返回错误.


我的问题是:

    如何读取tar文件,BytesIO()以便将其传递给put_archive()函数?

mar*_*eau 15

你可以这样做(未经测试,因为我没有Docker-py安装):

with open('keys.tar', 'rb') as fin:
    data = io.BytesIO(fin.read())
Run Code Online (Sandbox Code Playgroud)