Reading a tarfile into BytesIO
<p>I'm using <a href="https://docker-py.readthedocs.io/en/stable/api.html#docker.api.container.ContainerApiMixin.put_archive" rel="noreferrer">Docker-py</a> API to handle and manipulate <code>Docker</code> containers. In the <code>API</code>, the <code>put_archive()</code> function expects the <code>data</code> field to be in bytes.
So, using the <code>tarfile</code> library I have:</p>

<pre><code>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)
</code></pre>

<p>The API says:</p>

<blockquote>
  <p><strong><code>put_archive</code></strong>(<em><code>container</code></em>, <em><code>path</code></em>, <em><code>data</code></em>)</p>
  
  <p>&nbsp;&nbsp;&nbsp;&nbsp;Insert a file or folder in an existing container using a tar archive as source.</p>
  
  <p>&nbsp;&nbsp;&nbsp;&nbsp;<strong>Parameters</strong>:<br /></p>
  
  <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>container</strong> (<em>str</em>) – The container where the file(s) will be extracted.<br />
     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>path</strong> (<em>str</em>) – Path inside the container where the file(s) will be extracted. Must exist.<br />
     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>data</strong> (<em>bytes</em>) – tar data to be extracted<br /></p>
  
  <p>&nbsp;&nbsp;&nbsp;&nbsp;<strong>Returns</strong>: <strong><code>True</code></strong> if the call succeeds.<br /></p>
  
  <p>&nbsp;&nbsp;&nbsp;&nbsp;<strong>Return type:</strong> (bool)<br /></p>
  
  <p>&nbsp;&nbsp;&nbsp;&nbsp;<strong>Raises</strong>: <strong><code>docker.errors.APIError</code></strong> – If the server returns an error.</p>
</blockquote>

<hr>

<p>My question is:</p>

<p>&nbsp;&nbsp;&nbsp;&nbsp;How can I read the tar file as a <code>BytesIO()</code> so it can be passed to the <code>put_archive()</code> function?</p>