STEP INTO THE WORLD OF TECHNOLOGICAL INSIGHTS AND INNOVATION

Embedded Iron Python in WPF

Jul 14, 2015

Embedded_Iron_Python_in_WPF.jpg

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.

Embedded_iron_python_a_add_reference.jpg

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

Embedded_Iron_Python_b_add_reference.jpg

Code to Call IronPython from C#

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

Embedded_Iron_Python_c_call_iron_python.jpg

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.

Embedded_Iron_Python_d_call_python.jpg

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.

Embedded_Iron_Python_e_call_exeute.jpg

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.

Embedded_Iron_Python_f_event_raising_stream.jpg

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

Embedded_Iron_Python_g_write_output.jpg

Output

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

Embedded_Iron_Python_h_actual_output.jpg

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.

Sharepoint services

Previously:  Next up: 

Share

News Letter Sign up

Get in touch with us
phone_footer.png  +1 903-306-2430,
              +1 855-978-6816
 
contact-us.jpg