Python integration in c # application

I have the following problem: I have an old application written in python. This application allows the user to specify small python steps that will be executed, python steps are basically small python scripts, I call them steps, because the execution of this application includes other steps, such as executing something from the command line. These python steps are stored as python code in an XML file.

Now I want to rewrite the application using C # .NET. Is there a better solution to do something like this?

I don't want to call python as an external program and pass the actual python step (script) to the python interpreter - I want something to be embedded. I just stumbled across Python on IronPython and .NET, but I'm not quite sure which one to use. I want to achieve some debugging for small scripts, so calling the interpreter is not acceptable.

More importantly, many of these scenarios already exist. So I have to use the C # implementation for python, which has the same syntax as python, as well as the same built-in python libs. Is it possible?

Thank you and welcome Xeun

+7
source share
3 answers

IronPython is what you want. It compiles in .NET bytecode. You can easily call python code from another .NET language (and vice versa). I think IronPython is also supported in Visual Studio.

+6
source

Python scripts can be executed from C # using IronPython.

var ipy = Python.CreateRuntime(); dynamic test = ipy.UseFile("Test.py"); test.Simple(); 

See also:

http://putridparrot.com/blog/hosting-ironpython-in-ac-application/

and

https://blogs.msdn.microsoft.com/charlie/2009/10/25/running-ironpython-scripts-from-ac-4-0-program/

0
source

You can use IronPython ScriptScope.GetVariable to get the actual function, and then you can name it as a C # function. Use it like this:

C # code:

 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... 

It took a little time to finally figure it out, and it's pretty simple .. And IronPython is free and pretty easy to use. Hope this helps :)

0
source

All Articles