为什么.exe 单独运行可以,采用fsatapi后,就读取不到‘merged_df_power.csv‘了

# 运行测试用.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)})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值