4

I'm primarily a C# programmer, but have been left with a project that leaves me with 2 options:

  1. Call out to a python script (saved as a .py file) and process the return value, OR...
  2. Rewrite the whole python script (involving 6 .py files in total) in C#.

Naturally, Option 2 is a MAJOR waste of time if I can simply implement Option 1. Moreover, Option 1 is a learning opportunity, while Option 2 is a total geek copout.

So, my question is this: Is there a way to build a C# Process object to trigger the .py file's script AND catch the script's return value without using IronPython? I don't have anything against possibly using IronPython, I just need a solution as soon as possible, so if I can sidestep the I.P. learning curve until I have less urgent work to do, that would be optimal.

Thanks.

3 Answers3

6

Use Process.Start to run the Python script. In the ProcessStartInfo object, you specify:

  • FileName = the path and file name of the Python script.

  • Arguments = any arguments that you want to pass to the script.

  • RedirectStandardOutput = true (and RedirectStandardError if needed)

  • UseShellExecute = false

Then you get a Process object on which you can do some things, in particular:

  • Use Process.StandardOutput to read the Python script’s output. You could, for example, call ReadToEnd() on this to get a single string containing the entire output, or call ReadLine() in a loop.

  • Use Process.ExitCode to read the return code of the script.

  • Use Process.WaitForExit to wait for the script to finish.

Timwi
  • 65,159
  • 33
  • 165
  • 230
  • performance-wise, is there a difference between using IronPython and calling the script with Process.Start ? – gl3yn Jul 04 '23 at 09:30
2

Use System.Diagnostics.Process to run the Python script and then use Process.ExitCode to retrieve the return value of the script once it's done:

// Start the script
var process = System.Diagnostics.Process.Start("python MyScript.py");

// Wait for the script to run
process.WaitForExit();

int returnVal = process.ExitCode;
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
2

You can do something like:

Process py = new Process();
py.StartInfo.FileName = "python.exe";
py.StartInfo.Arguments = "c:\\python\\script.py";
py.StartInfo.UseShellExecute = false;
py.StartInfo.CreateNoWindow = true;
py.StartInfo.RedirectStandardOutput = true;
py.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
py.Start();
py.BeginOutputReadLine();
py.WaitForExit();
py.Close();

But, I must say that you can have multiple systems, based in different languages, since they can understand what each one says. I mean, there're some standards that can be thought to glue the whole thing. The python system can feed the C# system with JSON, XML, or some other standard, in a webservice built in Python, for example. Sometimes it's better to review your architecture.

Timwi
  • 65,159
  • 33
  • 165
  • 230
Alaor
  • 2,181
  • 5
  • 28
  • 40