python - 将 tarfile 读入 BytesIO

标签 python byte tar

我正在使用 Docker-py处理和操作 Docker 容器的 API。在 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)

API 说:

put_archive(container, path, data)

    Insert a file or folder in an existing container using a tar archive as source.

    Parameters:

        container (str) – The container where the file(s) will be extracted.
        path (str) – Path inside the container where the file(s) will be extracted. Must exist.
        data (bytes) – tar data to be extracted

    Returns: True if the call succeeds.

    Return type: (bool)

    Raises: docker.errors.APIError – If the server returns an error.


我的问题是:

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

最佳答案

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

with open('keys.tar', 'rb') as fin:
    data = io.BytesIO(fin.read())

关于python - 将 tarfile 读入 BytesIO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39603978/

相关文章:

find - 在 hp-ux 上压缩查找结果

unix - 使用 tar 和 grep 命令检查文件是否存在于 tar 文件中

python - 使用 'tarfile' 时跳过损坏的文件 (.tar.gz)

python - "Undirected"元组比较

Python记录打字时间

Python 3 将整数正确转换为字节 :

shell - 使用 shell 将字节插入文件

go - 在go中将字符串转换为字节

python - len(array) 在解释器中工作,在函数内调用时失败

python - 在 Windows 10 Pro 上运行 remote = False 时出现 GEKKO 错误