Search code examples
pythonc#exe

C# use program to excute EXE file from python


I had a file of exe , use cmd pyinstaller convert exe from python.

import csv
import math
import os
import sys
import random
InjectionFill_1Pressure=97.90995173159602
.
.
.
CoolingTime=15.469001397937381
with open('AI_MP01.csv', 'w', newline='') as outcsvfile_withopen:
writer = csv.writer(outcsvfile_withopen)
writer.writerow(['InjectionFill_1Pressure_p6100', ... ,'CoolingTime_p6171'])
writer.writerow([InjectionFill_1Pressure, ... ,'CoolingTime'])

If I excute the exe , I can get AI_MP01.csv. Like this enter image description here

I want use C# to excute the exe now, but exe did not output csv.

It is my code.

using System.Diagnostics;
private void button5_Click(object sender, EventArgs e)
{
/*example 1.
Process p = Process.Start(@"C:\Users\20111001\Desktop\AAA\ICAM_AI_20231027a\ICAM_AI\dist\ICAM_AI_final.exe");
p.WaitForExit();
*/
/*example 2.
string command = @"C:\Users\20111001\Desktop\AAA\ICAM_AI_20231027a\ICAM_AI\dist\ICAM_AI_final.exe";
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + command)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (Process proc = new Process())
{
proc.StartInfo = procStartInfo;
proc.Start();
return proc.StandardOutput.ReadToEnd();
}

example 1 can excute the exe , but exe did not output csv. example 2 have error. Like this enter image description here

the exe also set detail. enter image description here

Please help me.


Solution

  • The issue is most likely the working/current directory for the EXE. It looks like that Python code is assuming that the input file will be in the current directory. When you use Process.Start to run an EXE, the working directory will default to the same as for your .NET app, not the folder containing the EXE that you're executing. You need to set the WorkingDirectory of the ProcessStartInfo in order for the new process to use a different current directory. In your case, I think that should be something like this:

    var fileName = @"C:\Users\20111001\Desktop\AAA\ICAM_AI_20231027a\ICAM_AI\dist\ICAM_AI_final.exe";
    var psi = new ProcessStartInfo
              {
                  FileName = fileName,
                  WorkingDirectory = Path.GetDirectoryName(fileName)
              };
    
    using (var p = Process.Start(psi))
    {
        p.WaitForExit();
    }
    

    This is an example of why it is bad practice to use relative paths in your code and assume that they will refer to the same folder as your executable was run from. If you want to access that folder, specify it explicitly. That way, the current directory is irrelevant.