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

霸气de小男生 提交于 2020-03-05 03:19:52

问题


I have created a script using Python2.7 and compiled it using pyinstaller into an exe of the same name, in this case "GeneralStats.py" turns into "GeneralStats.exe" using --onefile and -w arguments.

When called with C# I use:

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

When called outside of C#, so in my local files I can run the .exe and the result is a text file with lots of values in (Running correctly).

However, when ran with C# in this format, I get an error that "GeneralStats returned -1!"

Which I have had issues with before, but it was a simple python error that when I returned to my code and ran it, I would receive an error that I overlooked. This time my python code returns no errors and works outside of C#.

Any ideas of why this could be? I can provide any code or file directories necessary, please just ask if you feel it would help with debugging.

EDIT:

Solved by removing:

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

And replacing with:

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

回答1:


You need to set the working directory for the Process - it is probably trying to load files from its working directory but isn't finding them.

See, e.g. 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.

Set it to the path where GeneralStats.exe is.



来源:https://stackoverflow.com/questions/54164715/pyinstaller-exe-works-locally-but-fails-when-called-by-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!