如何使用docker-py中的副本将文件从容器复制到主机

我正在使用docker-py。 我想从Docker容器复制文件到主机。

从docker-py文档:

copy Identical to the docker cp command. Get files/folders from the container. Params: container (str): The container to copy from resource (str): The path within the container Returns (str): The contents of the file as a string 

我可以创build容器并启动它,但无法获取从容器复制到主机的文件。 有人能帮我指出我是否失去了什么? 我有我的docker集装箱/mydir/myshell.sh我试图复制到主机。

 >>> a = c.copy(container="7eb334c512c57d37e38161ab7aad014ebaf6a622e4b8c868d7a666e1d855d217", resource="/mydir/myshell.sh") >>> a <requests.packages.urllib3.response.HTTPResponse object at 0x7f2f2aa57050> >>> type(a) <class 'requests.packages.urllib3.response.HTTPResponse'> 

如果有人能够帮助我确定是否复制或者不复制文件,这将是非常有帮助的。

copyput_archive不赞成使用的方法,首选方法是使用put_archive方法。 所以基本上我们需要创build一个档案,然后把它放到容器中。 我知道这听起来很奇怪,但这正是API目前所支持的。 如果你像我一样,认为这可以改善,随时打开一个问题/function的要求,我会upvote它。

以下是关于如何将文件复制到容器的代码片段:

 def copy_to_container(container_id, artifact_file): with create_archive(artifact_file) as archive: cli.put_archive(container=container_id, path='/tmp', data=archive) def create_archive(artifact_file): pw_tarstream = BytesIO() pw_tar = tarfile.TarFile(fileobj=pw_tarstream, mode='w') file_data = open(artifact_file, 'r').read() tarinfo = tarfile.TarInfo(name=artifact_file) tarinfo.size = len(file_data) tarinfo.mtime = time.time() # tarinfo.mode = 0600 pw_tar.addfile(tarinfo, BytesIO(file_data)) pw_tar.close() pw_tarstream.seek(0) return pw_tarstream 

在我的python脚本中,我添加了一个调用docker run -it -v artifacts:/artifacts target-build来运行docker的方法docker run -it -v artifacts:/artifacts target-build这样我就可以将我的文件从docker运行到artifacts文件夹中了。