Execute multiple python scripts using docker

Viewed 363

I want to execute multiple python scripts on Docker in same time.

But I've found something strange in output order.

Below is my test python script.

import random
import time


print("start test")

# sleep time
rn = random.randint(30, 45)

# file number
rn_fn = random.randint(0, 10000000)

print("sleep %s seconds ..." % rn)
time.sleep(rn)

print("write file python_test%s_%s ..." % (rn_fn, rn))

txt_file = open('/app/python_test%s_%s.txt' % (rn_fn, rn), 'w')
txt_file.write('test %s!' % rn_fn)
txt_file.close()

print("end write file")

When I run my python script twice on the CentOS7 with

python test.py &
python test.py &

The output is

00:00 - start test(1)
00:00 - start test(2)
00:00 - sleep 35 seconds ...(1)
00:00 - sleep 40 seconds ...(2)
00:35 - write file ~.txt(1)
00:35 - end write file(1)
00:40 - write file ~.txt(2)
00:40 - end write file(2)

But when I execute it on the docker with

docker exec -i container_name /app/test.py &
docker exec -i container_name /app/test.py &

The output is

00:00 - start test(1)
00:00 - sleep 35 seconds ...(1)
00:35 - write file ~.txt(1)
00:35 - end write file(1)
00:00 - start test(2)
00:00 - sleep 40 seconds ...(2)
00:40 - write file ~.txt(2)
00:40 - end write file(2)

Why the print() order is different in centOS and docker?

Does docker prints when its process ends?

1 Answers

If you run the Python script from a Docker container, it does not have a tty by default, you have to add --tty , -t when you are about to run your container,

docker run -t yourimage

You could force Python to flush, if you do not want the container to do so, by adding the flush parameter in your print method.

print("Begin", flush=True)

Related