Search code examples
pythondockercontainersdevopsdockerpy

docker python how to echo into a file


I am using python3 with docker-py in order to run dockers and perform some operations.

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.

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')

What am i missing here? how can I use a command to output into the file?


Solution

  • 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

    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

    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()