pyinstaller .exe 在本地工作但在 C# 调用时失败?

pyinstaller .exe works locally but fails when called by C#?

我使用 Python2.7 创建了一个脚本,并使用 pyinstaller 将其编译成同名的 exe,在这种情况下 "GeneralStats.py" 使用 --onefile 变成 "GeneralStats.exe"和 -w 参数。

当用 C# 调用时,我使用:

var pythonDirectory = (Directory.GetCurrentDirectory());
var filePathExe1 = Path.Combine(pythonDirectory + "\Python\GeneralStats.exe");
Process.Start(filePathExe1);

当在 C# 外部调用时,因此在我的本地文件中我可以 运行 .exe 结果是一个包含大量值的文本文件(运行 正确)。

但是,当 运行 以这种格式使用 C# 时,我得到一个错误 "GeneralStats returned -1!"

我之前遇到过问题,但这是一个简单的 python 错误,当我返回我的代码并 运行 它时,我会收到一个我忽略的错误。 这次我的 python 代码 returns 没有错误并且在 C# 之外工作。

知道为什么会这样吗?我可以提供任何必要的代码或文件目录,请问你是否觉得它有助于调试。

编辑:

通过删除解决:

var filePathExe1 = Path.Combine(pythonDirectory + "\Python\GeneralStats.exe");
Process.Start(filePathExe1);

并替换为:

ProcessStartInfo _processStartInfo = new ProcessStartInfo();
_processStartInfo.WorkingDirectory = Path.Combine(pythonDirectory + "\Python");
_processStartInfo.FileName = @"GeneralStats.exe";
_processStartInfo.CreateNoWindow = true;
Process myProcess = Process.Start(_processStartInfo);

您需要为 Process 设置工作目录 - 它可能正在尝试从其工作目录加载文件但未找到它们。

参见,例如this:

Use the ProcessStartInfo.WorkingDirectory property to set it prior to starting the process. If the property is not set, the default working directory is %SYSTEMROOT%\system32.

设置为GeneralStats.exe所在的路径。