Pixentia Insights

Embedded Iron Python in WPF

Written by Pixentia | Jul 14, 2015 6:00:00 AM

Overview:

IronPython is an implementation of the Python language which runs on the .NET Framework. It means, it is a collection of .NET assemblies that allow us to compile and execute Python code as a .NET language such as C#, Visual Basic etc. This blog gives a detailed info on how to write a C# program which runs the python script using IronPython .

Prerequisite:

After the IronPython installation, its interpreter and libraries will be installed in your Program Files directory. The interpreter is installed in ipy.exe, where ipy is pronounced as “Eye-Pie”. The interpreter remains dormant until you call Python from C#.

Implementation

  • Add References

The following statements include the IronPython and Microsoft Dynamic Language Runtime (DLR) namespaces in your C# file.

To run a Python script inside a C# program, you should include some or all of the libraries listed below,

Code to Call IronPython from C#

  • Write a simple script that you want to run given as follows :

Above code is a simple python script which will print 10 numbers in a loop with 1 sec interval for every loop increment.

Write code to call the python script.

  • We need to create an instance of the python runtime environment.

The call to CreateRunTime loads or sets up the core Python libraries and the DLR code needed to execute the Python script.

  • Call ExecuteFile (FilePath) to load our simple Python script into memory.

EventRaisingStreamWriter is used to raise event whenever the python script redirects the output.i.e., when the MemoryStream() receives the output, it raises the event.

The method writeOutput() appends text to the TextBox control (called ResultBox).

Output

Output from the C# program which runs the python script using IronPython is as given below :

Pixentia is an enthusiastic family of individuals, fervent to make lives simpler through effective use of technology. Our mission is to implement solutions that drives business results. Know more insights from our thoughts and experience.

Contact us today or call 1-855-978-6816 to talk with us about your business needs.