IronPython

IronPython is an open-source implementation of the Python programming language which is tightly integrated with .NET. 

IronPython can use .NET and Python libraries, and other .NET languages can use Python code just as easily.

Why IronPython?

IronPython is an excellent addition to .NET, providing Python developers with the power of the .NET. Existing .NET developers can also use IronPython as a fast and expressive scripting language for embedding, testing, or writing a new application from scratch.

The CLR is a great platform for creating programming languages, and the DLR makes it all the better for dynamic languages. 


Calling (Iron)Python code from a C# app?

The process is simple, especially in a C#/.NET 4 application where support for dynamic languages have been improved via usage of the dynamic type. But it all ultimately depends on how you intend to use the (Iron)Python code within your application. You could always run ipy.exe as a separate process and pass your source files in so they may be executed. But you probably wanted to host them in your C# application. That leaves you with many options.

  1. Add a reference to the IronPython.dll and Microsoft.Scripting.dll assemblies. You'll usually find them both in your root IronPython installation directory.
  2. Add using IronPython.Hosting; to the top of your source and create an instance of the IronPython scripting engine using Python.CreateEngine().
  3. You have a couple of options from here but basically you'd create a ScriptScope or ScriptSource and store it as a dynamic variable. This allows you to execute it or manipulate the scopes from C# if you choose to do so.


C# code

Using CreateScope() to create an empty ScriptScope to use directly in C# code but usable in Python sources. You can think of these as your global variables within an instance of the interpreter.

var var1,var2;

ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
engine.ExecuteFile(@"C:\test.py", scope);
dynamic testFunction = scope.GetVariable("test_func");
var result = testFunction(var1,var2);


Python code

def test_func(var1,var2):
    ...do something...


Practical steps to get ironPython

 1)Need to install

Install-Package DynamicLanguageRuntime -Version 1.2.2

2) Need to add "Iropython.dll" using this: https://www.webucator.com/how-to/how-add-references-your-visual-studio-project.cfm

3) Need to Use

using IronPython.Hosting;
using IronPython.Runtime;
using IronPython;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting;

3) Need to set var

ScriptEngine engine = Python.CreateEngine();


Comments

Popular posts from this blog

Email Sending through O365 using OAuth Protocol

IISRESET vs App Pool Recycling ?

Deploy .Net6.0 Web api with docker