我想同時(shí)在 Docker 上執(zhí)行多個(gè) python 腳本。但我發(fā)現(xiàn)輸出順序有些奇怪。下面是我的測試 python 腳本。import randomimport timeprint("start test")# sleep timern = random.randint(30, 45)# file numberrn_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")當(dāng)我在 CentOS7 上運(yùn)行 python 腳本兩次時(shí)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)但是當(dāng)我在 docker 上執(zhí)行它時(shí)docker exec -i container_name /app/test.py &docker exec -i container_name /app/test.py &輸出是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 進(jìn)程結(jié)束時(shí)是否打???
1 回答

狐的傳說
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
如果您從 Docker 容器運(yùn)行 Python 腳本,默認(rèn)情況下它沒有 tty,當(dāng)您要運(yùn)行容器時(shí),您必須--tty
添加-t
,
docker run -t yourimage
如果您不希望容器執(zhí)行此操作,您可以通過在打印方法中添加flush參數(shù)來強(qiáng)制Python進(jìn)行刷新。
print("Begin", flush=True)
添加回答
舉報(bào)
0/150
提交
取消