# 运行测试用.exe的接口
@app.get("/run-test-exe")
async def run_test_exe():
global exe_process, log_queue
try:
exe_path = r"E:\打包用\dist\测试用.exe"
if not os.path.exists(exe_path):
return JSONResponse({"status": "error", "message": "测试用.exe文件不存在"})
# 清空日志队列
while not log_queue.empty():
log_queue.get()
# 启动exe并捕获输出
exe_process = subprocess.Popen(
exe_path,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1
)
# 异步读取输出到队列
async def read_output():
start_time = datetime.now()
for line in exe_process.stdout:
log_queue.put(line.strip())
# 计算程序运行时间
end_time = datetime.now()
duration = (end_time - start_time).total_seconds()
# 保存计算记录
save_calculation_record(round(duration, 1))
exe_process.wait()
asyncio.create_task(read_output())
return JSONResponse({"status": "success", "message": "测试用.exe已启动"})
except Exception as e:
return JSONResponse({"status": "error", "message": str(e)})
报错:
Traceback (most recent call last):
File "简化版.py", line 19, in
File "pandas\io\parsers\readers.py", line 1026, in read_csv
File "pandas\io\parsers\readers.py", line 620, in _read
File "pandas\io\parsers\readers.py", line 1620, in __init__
File "pandas\io\parsers\readers.py", line 1880, in _make_engine
File "pandas\io\common.py", line 873, in get_handle
FileNotFoundError: [Errno 2] No such file or directory: 'merged_df_power.csv'
[PYI-9452:ERROR] Failed to execute script '???' due to unhandled exception!
错误原因:
关键原因:工作目录差异
-
单独运行
.exe时:默认工作目录是.exe所在的目录(例如E:\打包用\dist\或E:\发布版\dist\),此时.exe内部若用相对路径读取merged_df_power.csv(如./merged_df_power.csv),会在自身目录下查找,因此能找到文件。 -
通过 FastAPI 调用时:
.exe的工作目录默认是 FastAPI 程序的运行目录(即 main.py 所在的目录),而非.exe自身的目录。如果.exe内部用相对路径读取merged_df_power.csv,会去 FastAPI 运行目录下查找,而该目录下没有此文件,导致FileNotFoundError。
解决方案:指定 .exe 的工作目录
在 FastAPI 中调用 .exe 时,通过 subprocess.Popen 的 cwd 参数,强制指定 .exe 的工作目录为其自身所在的目录(确保与单独运行时的工作目录一致)。
需要修改代码中所有调用 .exe 的接口(/run-test-exe、/run-exe、/run-classification-exe),以 /run-test-exe 为例:
@app.get("/run-test-exe")
async def run_test_exe():
global exe_process, log_queue
try:
exe_path = r"E:\打包用\dist\测试用.exe"
# 提取.exe所在的目录(作为工作目录)
exe_dir = os.path.dirname(exe_path) # 得到 "E:\打包用\dist"
if not os.path.exists(exe_path):
return JSONResponse({"status": "error", "message": "测试用.exe文件不存在"})
# 清空日志队列
while not log_queue.empty():
log_queue.get()
# 启动exe时,通过cwd指定工作目录为.exe所在目录
exe_process = subprocess.Popen(
exe_path,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
cwd=exe_dir # 关键:指定工作目录
)
# 异步读取输出到队列(其余代码不变)
async def read_output():
start_time = datetime.now()
for line in exe_process.stdout:
log_queue.put(line.strip())
exe_process.wait()
end_time = datetime.now()
duration = (end_time - start_time).total_seconds()
save_calculation_record(round(duration, 1))
asyncio.create_task(read_output())
return JSONResponse({"status": "success", "message": "测试用.exe已启动"})
except Exception as e:
return JSONResponse({"status": "error", "message": str(e)})

被折叠的 条评论
为什么被折叠?



