重点看popen那里,如何与下面输入输出做配合
日志的实时写入关键就是f.flush(),它会将缓冲区的写入文件中,就可以做到类似于实时的写入效果。
cmd = f"python train_model.py --mode {mode} --task_id {task_id} --sql_info {sql_info} --mode_id {mode_id} " \
f"--version {version} --module_id {module_ids} --record_uid {record_uid} --data_table_name {constant.TABLE_TRAIN_DATA} " \
f"--label_table_name {constant.TABLE_LABELS}"
generic_components.green_printer("执行命令:" + cmd)
logs_dir = os.path.join(constant.MODE_PATH, mode_id, "logs")
generic_components.check_dir_exists(logs_dir)
logFile_path = os.path.join(logs_dir, f"{task_id}.log")
cmd_result = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
bufsize=1, shell=True)
with open(logFile_path, "a+", encoding="utf-8") as f:
for line in iter(cmd_result.stdout.readline, b''):
line = line.strip()
line = str(line, encoding='utf-8')
print(line)
f.write(line + "\n")
f.flush()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20