使用docker执行多个python脚本
我想在Docker上同时执行多个python脚本 但我发现输出顺序有些奇怪 下面是我的测试python脚本使用docker执行多个python脚本,python,docker,Python,Docker,我想在Docker上同时执行多个python脚本 但我发现输出顺序有些奇怪 下面是我的测试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)
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")
当我在CentOS7上用
python test.py &
python test.py &
输出是
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)
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)
但当我在docker上用
docker exec -i container_name /app/test.py &
docker exec -i container_name /app/test.py &
输出是
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)
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)
为什么centOS和docker的print()顺序不同
docker进程结束时是否打印?如果从docker容器运行Python脚本,默认情况下它没有tty,则在即将运行容器时,必须添加
--tty
,-t
docker run-t yourimage
如果不希望容器刷新,可以通过在print方法中添加flush参数来强制Python刷新
print(“Begin”,flush=True)
您是否尝试过docker exec-i container\u name bash-c'/app/test.py&/app/test.py&'
?我尝试过,但输出相同。我认为tty(-t)选项会影响输出。我不知道print方法有那个参数。谢谢你的回答。