Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python & C#: Is IronPython absolutely necessary?

Tags:

python

c#

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.

like image 609
Felix Cartwright Avatar asked Dec 29 '22 07:12

Felix Cartwright


1 Answers

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.

like image 60
Timwi Avatar answered Jan 06 '23 17:01

Timwi