Capturing output of python script run inside a docker container

前端 未结 2 1200
说谎
说谎 2020-12-24 02:05

The aim here is to use a docker container as a secure sandbox to run untrusted python scripts in, but to do so from within python using the docker-py module, and be able to

相关标签:
2条回答
  • 2020-12-24 02:52

    You may experience a race condition since the started container is running in parallel to your control program. You need to wait for your container to start and finish before grabbing the logs. Add a docker.wait to your code right after docker.start.

    docker.wait(contid)
    

    Your output seems empty because nothing has yet been logged.

    0 讨论(0)
  • 2020-12-24 02:56

    You are experiencing this behavior because python buffers its outputs by default.

    Take this example:

    vagrant@docker:/vagrant/tmp$ cat foo.py
    #!/usr/bin/python
    from time import sleep
    
    while True:
        print "f00"
        sleep(1)
    

    then observing the logs from a container running as a daemon does not show anything:

    vagrant@docker:/vagrant/tmp$ docker logs -f $(docker run -d -v $(pwd):/app dockerfile/python python /app/foo.py)
    

    but if you disable the python buffered output with the -u command line parameter, everything shows up:

    vagrant@docker:/vagrant/tmp$ docker logs -f $(docker run -d -v $(pwd):/app dockerfile/python python -u /app/foo.py)
    f00
    f00
    f00
    f00
    

    You can also inject the PYTHONUNBUFFERED environment variable:

    vagrant@docker:/vagrant/tmp$ docker logs -f $(docker run -d -v $(pwd):/app -e PYTHONUNBUFFERED=0 dockerfile/python python /app/foo.py)
    f00
    f00
    f00
    f00
    

    Note that this behavior affects only containers running without the -t or --tty parameter.

    0 讨论(0)
提交回复
热议问题