Python is a great programming language. It also has fantastic libraries (e.g. numPy, sciPy, pandas, etc.) that can significantly simplify and speed-up development. So, it is no surprise that sometimes when considering a coding solution for some problem you scratch your head and wish if you could only do it in Python (i.e. instead of C# or other low level programming language)!
In this short post I will show you how to execute a Python scrip and capture its output from a C# console-based program. Essentially, running a Python script from C# can be done either with IronPython dll referenced within your C# project and using the IronPython.Hosting library; or via kicking off a process that executes a Python program. The advantage of the later is that the script can be written in any Python flavor, provided you have installed the Python shell compatible with the script.
For this example I am using the following Python program saved as ‘hello.py’:
import sys def main(): print('Hello') if len(sys.argv)>=3: x = sys.argv[1] y = sys.argv[2] # print concatenated parameters print(x+y) if __name__=='__main__': main()
The following C# code will start a process and assign it to the Python interpreter with the Python program name passed as argument. The output is parsed as stream. However, the output can be written to a file instead.
using System; using System.Diagnostics; using System.IO; using System.Threading.Tasks; namespace ExecutingPythonScript { class EntryPoint { static void Main(string[] args) { int x = 1; int y = 2; string progToRun = "C:\\Python27\\hello.py"; char[] splitter = {'\r'}; Process proc = new Process(); proc.StartInfo.FileName = "python.exe"; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.UseShellExecute = false; // call hello.py to concatenate passed parameters proc.StartInfo.Arguments = string.Concat(progToRun, " ", x.ToString(), " ", y.ToString()); proc.Start(); StreamReader sReader = proc.StandardOutput; string[] output = sReader.ReadToEnd().Split(splitter); foreach (string s in output) Console.WriteLine(s); proc.WaitForExit(); Console.ReadLine(); } } }
And that is all. It is that simple. One last thing to point out: progToRun could have been a string literal assigned to the actual Python code. This works well when you have a small task and don’t want to write a Python program to hold it.
***Thanks to Johannes for spotting a coding type in the variable name, which is now fixed.