简体   繁体   English

docker python如何回显到文件

[英]docker python how to echo into a file

I am using python3 with docker-py in order to run dockers and perform some operations. 我将python3与docker-py结合使用,以运行dockers并执行一些操作。

I am creating a container, and would like to echo something to a file in the mounted directory, but instead of outputting into the file, it outputs into stdout. 我正在创建一个容器,并想在挂载目录中向文件回显某些内容,但不是输出到文件中,而是输出到stdout中。

this is the code 这是代码

import docker
client = docker.from_env()

cont = client.containers.create("continuumio/anaconda3", volumes={
"/home/user/zbp/rundir": {"bind": "/data", "mode": "rw"}
}, command="sleep 1000")

cont.start()
log = cont.exec_run(["echo", "1", ">>", "/data/sada.txt"],
                    stderr=True, stdout=True)

and the output is 

ExecResult(exit_code=0, output=b'1 >> /data/sada.txt\\n') ExecResult(exit_code = 0,output = b'1 >> /data/sada.txt\\n')

What am i missing here? 我在这里想念什么? how can I use a command to output into the file? 如何使用命令输出到文件?

I suppose this is the expected behaviour of docker exec , You may need to open a shell and wrap your commands so that you can redirect the output to a file 我想这是docker exec的预期行为,您可能需要打开外壳并包装命令,以便可以将输出重定向到文件

log = cont.exec_run(["sh -c ", "echo 1 >> /data/sada.txt",],
                    stderr=True, stdout=True)

I haven't tested this code , Please modify the above snippet for your need 我尚未测试此代码,请根据需要修改以上代码段

Adding the tested code which is working perfectly , FYI I have used ubuntu image 添加已正常运行的测试代码,仅供参考,我使用了ubuntu图片

import docker
client = docker.from_env()

cont = client.containers.create("ubuntu", volumes={
"/tmp/dockerdata": {"bind": "/data", "mode": "rw"}
}, command="sleep 100000")

cont.start()
log = cont.exec_run("sh -c 'ls -l  >> /data/out.txt'",
                    stderr=True, stdout=True)
for line in log:
    print(line, end='')

cont.stop()
print(cont.status)
cont.remove()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM