[英]How to copy a file from host to container using docker-py (docker SDK)
I know, there is possible way how to copy file bidirectionally between host and docker container using docker cp
and also it is possible to obtain file from running container using docker-py.我知道,有可能如何使用docker cp
在主机和 docker 容器之间双向复制文件,也可以使用 docker-py 从正在运行的容器中获取文件。 But I am not able to figure out how (or if it is even possible) copy file from host to running container using docker-py.但我无法弄清楚如何(或者甚至可能)使用 docker-py 将文件从主机复制到正在运行的容器。 Do you guys have any experiences with such kind of problem?各位有遇到此类问题的经验吗? Is it possible to do or I have to execute command using python os.system
.是否可以这样做,或者我必须使用 python os.system
执行命令。 I would like to avoid this solution.我想避免这种解决方案。
Something like this should work:像这样的东西应该工作:
import os
import tarfile
import docker
client = docker.from_env()
def copy_to(src, dst):
name, dst = dst.split(':')
container = client.containers.get(name)
os.chdir(os.path.dirname(src))
srcname = os.path.basename(src)
tar = tarfile.open(src + '.tar', mode='w')
try:
tar.add(srcname)
finally:
tar.close()
data = open(src + '.tar', 'rb').read()
container.put_archive(os.path.dirname(dst), data)
And then use it like:然后像这样使用它:
copy_to('/local/foo.txt', 'my-container:/tmp/foo.txt')
Code snippet using memory BytesIO:使用内存 BytesIO 的代码片段:
def copy_to_container(container: 'Container', src: str, dst_dir: str):
""" src shall be an absolute path """
stream = io.BytesIO()
with tarfile.open(fileobj=stream, mode='w|') as tar, open(src, 'rb') as f:
info = tar.gettarinfo(fileobj=f)
info.name = os.path.basename(src)
tar.addfile(info, f)
container.put_archive(dst_dir, stream.getvalue())
#!/usr/bin/python #!/usr/bin/python
import os import tarfile import docker导入 os 导入 tarfile 导入 docker
client = docker.from_env()客户端 = docker.from_env()
def copy_to(src, dst): name, dst = dst.split(':') container = client.containers.get(name) def copy_to(src, dst): name, dst = dst.split(':') container = client.containers.get(name)
os.chdir(os.path.dirname(src))
srcname = os.path.basename(src)
tar = tarfile.open(srcname + '.tar', mode='w')
obj=os.walk(srcname)
for items in obj:
for files in items[2]:
if files[-4::] == ".csv" :
abs_path = items[0] + "/" + files
tar.add(abs_path)
tar.close()
data = open(srcname + '.tar', 'rb')
container.put_archive(dst, data)
data.close()
copy_to('source_directory', 'container_name:destination_directory') copy_to('source_directory', 'container_name:destination_directory')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.