简体   繁体   English

使用docker执行多个python脚本

[英]Execute multiple python scripts using docker

I want to execute multiple python scripts on Docker in same time.我想同时在 Docker 上执行多个 python 脚本。

But I've found something strange in output order.但是我发现输出顺序有些奇怪。

Below is my test python script.下面是我的测试 python 脚本。

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当我在 CentOS7 上运行我的 python 脚本两次时

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 上执行它时

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?为什么centOS 和docker 的print() 顺序不同?

Does docker prints when its process ends? docker 在进程结束时是否打印?

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 容器运行 Python 脚本,默认情况下它没有 tty,您必须在即将运行容器时添加--tty-t

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.如果您不希望容器这样做,您可以通过在打印方法中添加 flush 参数来强制 Python 刷新。

print("Begin", flush=True)

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

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