Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a tarfile into BytesIO

Tags:

python

tar

byte

I'm using Docker-py API to handle and manipulate Docker containers. In the API, the put_archive() function expects the data field to be in bytes. So, using the tarfile library I have:

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)

The API says:

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.


My question is:

    How can I read the tar file as a BytesIO() so it can be passed to the put_archive() function?

like image 747
cybertextron Avatar asked Sep 20 '16 21:09

cybertextron


People also ask

How do I read a tar file in Python?

You can use the tarfile module to read and write tar files. To extract a tar file, you need to first open the file and then use the extract method of the tarfile module.

Is BytesIO a file like object?

StringIO and BytesIO are methods that manipulate string and bytes data in memory. StringIO is used for string data and BytesIO is used for binary data. This classes create file like object that operate on string data. The StringIO and BytesIO classes are most useful in scenarios where you need to mimic a normal file.

What is tarfile in python?

The tarfile module makes it possible to read and write tar archives, including those using gzip, bz2 and lzma compression. Use the zipfile module to read or write . zip files, or the higher-level functions in shutil.


1 Answers

You could do this way (untested because I don't haveDocker-py installed):

with open('keys.tar', 'rb') as fin:
    data = io.BytesIO(fin.read())
like image 76
martineau Avatar answered Oct 27 '22 10:10

martineau