From 5ede29efd4a00a9af2eb17cc536fbad739091ca7 Mon Sep 17 00:00:00 2001 From: DingZQ Date: Mon, 2 Jun 2025 19:02:13 +0800 Subject: [PATCH] Add simulation informaiton to log --- epanet/epanet.py | 69 +++++++++--------------------------------------- 1 file changed, 12 insertions(+), 57 deletions(-) diff --git a/epanet/epanet.py b/epanet/epanet.py index acf42cd..8d67e59 100644 --- a/epanet/epanet.py +++ b/epanet/epanet.py @@ -4,6 +4,7 @@ import os import sys import json import base64 +from datetime import datetime import subprocess import logging from typing import Any @@ -288,79 +289,33 @@ def run_project(name: str, readable_output: bool = False) -> str: inp = os.path.join(os.path.join(dir, 'db_inp'), input + '.inp') rpt = os.path.join(os.path.join(dir, 'temp'), input + '.rpt') opt = os.path.join(os.path.join(dir, 'temp'), input + '.opt') + command = f'{exe} {inp} {rpt} {opt}' - print(command) + logging.info(f"Run simulation at {datetime.now()}") + logging.info(command) data = {} # DingZQ, 2025-06-02, 使用subprocess.Popen捕获输出到全局日志, 原来的代码是这么写的 - # result = os.system(command) - - """ - 执行带参数的外部exe并捕获输出到全局日志 - - :param exe_path: exe文件路径 - :param arguments: 命令行参数列表 - :param timeout: 执行超时时间(秒) - :return: 进程退出状态码 - """ - result = -1 - try: - # 启动子进程 - with subprocess.Popen( - command, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, # 合并错误输出和标准输出 - text=True, # 文本模式(Python 3.7+) - bufsize=1, # 行缓冲 - encoding='utf-8', # 编码设置 - errors='replace' # 编码错误处理方式 - ) as process: - - # 实时读取输出流 - while True: - output_line = process.stdout.readline() - error_line = process.stderr.readline() - if output_line == '' and process.poll() is not None: - break - - if error_line == '' and process.poll() is not None: - break - - if output_line: - stripped_line = output_line.rstrip() - logging.info(f"EXE_OUTPUT: {stripped_line}") - - if error_line: - stripped_line = error_line.rstrip() - logging.error(f"EXE_ERROR: {stripped_line}") - - # 获取退出状态码 - returncode = process.poll() - - # 记录结束状态 - logging.info("-" * 60) - if returncode == 0: - logging.info(f"成功结束! 退出码: {returncode}") - else: - logging.error(f"异常结束! 退出码: {returncode}") - - result = returncode - - except Exception as e: - logging.exception(f"执行过程中出错: {str(e)}") - result = -1 # 自定义错误码 + result = os.system(command) + logging.info(f"Simulation result: {result}") if result != 0: data['simulation_result'] = 'failed' + + logging.error('simulation failed') + else: data['simulation_result'] = 'successful' + logging.info('simulation successful') + if readable_output: data |= _dump_output(opt) else: data['output'] = dump_output_binary(opt) data['report'] = dump_report(rpt) + logging.info(f"Report: {data['report']}") return json.dumps(data)