Saturday, 9 February 2019

Call python code in C# using IronPython

Why it’s required?

Python has lots of  useful library that we can utilise in our application and get that functionality in our webapplication. So just trying how to get the python features in MVC applications.

Using the Ironpython  to call the python code in C# code.  Follow the steps and use the below code to call the python code.

1.       Taking the reference of IronPython  using the Nuget Package as like below.

2.       Write a small python code as like below it is small code for hello world

So in method it  is expecting the parameter and provide the result as Hello + <parameter>
Output : Hello satya

3.       Now take the reference of Ironpython in application
4.       Code for reading the python file in C# code is like below:

public ActionResult Index()
            ScriptRuntime scriptRuntime = IronPython.Hosting.Python.CreateRuntime();

            string path = Server.MapPath("~/python/");

            ScriptScope scope = scriptRuntime.ExecuteFile(path);

            Func<string, string> hello = scope.GetVariable<Func<string, string>>("hello");

            string str = hello("satya");

            ViewBag.Message = str;
            return View();

Calling the python method into code with be written in line as:

Func<string, string> hello = scope.GetVariable<Func<string, string>>("hello");

To pass the parameter to the method has written as below:

string str = hello("satya");

You can see the output in debug mode as like below:

Above output is the similar output which we received  in calling the python function in python console output.

No comments:

Post a Comment