我正在使用 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 extractedReturns:
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/