我想同時在 Docker 上執行多個 python 腳本。但我發現輸出順序有些奇怪。下面是我的測試 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")當我在 CentOS7 上運行 python 腳本兩次時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)但是當我在 docker 上執行它時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 進程結束時是否打???
1 回答

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