求助:使用C#调用PyInstaller生成的EXE无法输出CSV文件
问题解决方案
核心问题:工作目录不匹配
手动运行EXE时,程序的工作目录默认是EXE所在文件夹,所以CSV会生成在这个路径下。但C#调用Process时,默认工作目录是C#应用自身的运行目录(比如bin/Debug),导致Python脚本生成的CSV不在你预期的位置,误以为没有输出;示例2则存在语法和错误处理缺失的问题。
针对示例1的修复
修改Process的工作目录为EXE所在路径,同时优化Python脚本的CSV生成路径,彻底避免依赖工作目录:
C#代码调整
using System.Diagnostics; using System.IO; // 需要添加这个命名空间 private void button5_Click(object sender, EventArgs e) { string exePath = @"C:\Users\20111001\Desktop\AAA\ICAM_AI_20231027a\ICAM_AI\dist\ICAM_AI_final.exe"; ProcessStartInfo startInfo = new ProcessStartInfo(exePath) { // 强制将工作目录设置为EXE所在文件夹 WorkingDirectory = Path.GetDirectoryName(exePath) }; using (Process p = Process.Start(startInfo)) { p.WaitForExit(); } }
Python脚本优化(推荐)
直接用绝对路径生成CSV,彻底摆脱工作目录限制:
import csv import math import os import sys import random InjectionFill_1Pressure=97.90995173159602 ... CoolingTime=15.469001397937381 # 获取EXE所在的绝对路径 exe_dir = os.path.dirname(sys.executable) csv_path = os.path.join(exe_dir, 'AI_MP01.csv') with open(csv_path, 'w', newline='') as outcsvfile_withopen: writer = csv.writer(outcsvfile_withopen) writer.writerow(['InjectionFill_1Pressure_p6100', ... ,'CoolingTime_p6171']) # 注意:原代码最后一行的'CoolingTime'是字符串,改为变量名才能写入数值 writer.writerow([InjectionFill_1Pressure, ... ,CoolingTime])
针对示例2的修复
示例2存在语法不完整(缺少闭合大括号)、未处理错误输出的问题,调整后代码如下:
using System.Diagnostics; using System.IO; using System.Windows.Forms; // 如果是WinForms应用 private void button5_Click(object sender, EventArgs e) { string exePath = @"C:\Users\20111001\Desktop\AAA\ICAM_AI_20231027a\ICAM_AI\dist\ICAM_AI_final.exe"; ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", $"/c \"{exePath}\"") { RedirectStandardOutput = true, RedirectStandardError = true, // 新增:捕获错误输出,方便排查问题 UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = Path.GetDirectoryName(exePath) }; using (Process proc = new Process()) { proc.StartInfo = procStartInfo; proc.Start(); // 先读错误输出再读正常输出,避免进程死锁 string errorMsg = proc.StandardError.ReadToEnd(); string outputMsg = proc.StandardOutput.ReadToEnd(); proc.WaitForExit(); // 如果有错误,弹窗提示 if (!string.IsNullOrEmpty(errorMsg)) { MessageBox.Show($"运行出错:{errorMsg}"); } } }
额外排查点
- 权限问题:如果EXE所在目录需要管理员权限,C#程序也需以管理员身份运行。
- 依赖缺失:通过
RedirectStandardError捕获的错误信息,可以排查PyInstaller打包时是否遗漏了依赖库。 - 变量引用错误:原Python脚本最后一行的
'CoolingTime'是字符串,必须改为变量名CoolingTime才能写入正确的数值。
内容的提问来源于stack exchange,提问作者xeroxion
相关产品推荐
相关产品推荐

