Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

docker stucks when executing time.sleep(1) in a python loop

With the use of docker-compose and python:2.7, it runs correctly when executing only while 1 loop and time.sleep(1) separately.

But it stucks when executing them together.

Here is the docker version and the file content on my mac

tmp docker -v
Docker version 1.12.5, build 7392c3b
tmp cat docker-compose.yml
version: '2'
services:
    test:
        image: python:2.7
        command: [python, -c, "print 0\nwhile 1:\n\tprint 1\n\tbreak"]
tmp docker-compose up
Creating network "tmp_default" with the default driver
Creating tmp_test_1
Attaching to tmp_test_1
test_1  | 0
test_1  | 1
tmp_test_1 exited with code 0
tmp cat docker-compose.yml
version: '2'
services:
    test:
        image: python:2.7
        command: [python, -c, "print 0\nimport time\nprint time.sleep(1)"]
tmp docker-compose up
Recreating tmp_test_1
Attaching to tmp_test_1
test_1  | 0
test_1  | None
tmp_test_1 exited with code 0
tmp cat docker-compose.yml
version: '2'
services:
    test:
        image: python:2.7
        command: [python, -c, "print 0\nimport time\nwhile 1:\n\tprint time.sleep(1)"]
tmp docker-compose up
Recreating tmp_test_1
Attaching to tmp_test_1

and here it stucks.

Hope to know the reason and the method to fix it, thanks.

like image 531
Roy Avatar asked Feb 14 '17 10:02

Roy


People also ask

What is time sleep 1 in Python?

Python time sleep function is used to add delay in the execution of a program. We can use python sleep function to halt the execution of the program for given time in seconds. Notice that python time sleep function actually stops the execution of current thread only, not the whole program.

What is docker sleep command?

What is the usual reason to use sleep as a command to run a docker container? A docker container will live until the command it runs finishes. This command is normally set in the Dockerfile used to build the image (in a CMD stanza) and can be overridden on the command line (as in the above examples).

Why my docker run exits immediately?

You're running a shell in a container, but you haven't assigned a terminal: If you're running a container with a shell (like bash ) as the default command, then the container will exit immediately if you haven't attached an interactive terminal.


1 Answers

Add -u flag to python in order to have unbuffered stdout:

command: [python, -uc, "print 0\nimport time\nwhile 1:\n\tprint time.sleep(1)"]
like image 70
fernandezcuesta Avatar answered Oct 20 '22 19:10

fernandezcuesta