Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

IronPython and C#


What is IronPython

IronPython is an open-source implementation of the Python programming language which is tightly integrated with the .Net Framework.
IronPython can use the .Net Framework and python libraries,and other .NET languaages can use Python code just as easily

In this post I will show you how to call Python method in c#.


Create a new Console application and visual studio
Right click on the project and click on Manage Nuget Packages and search for IronPython

After installing IronPython import following namespaces
using Microsoft.Scripting.Hosting;

Right click on project and add new file Calculator.py and add following python code


def add(a,b):
    return a+b

Open Program.cs file and add following code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Scripting.Hosting;
namespace IronPython_Tut1
{
    class Program
    {
    static void Main(string[] args)
        {
    //Create runtime
            ScriptRuntime runtime = IronPython.Hosting.Python.CreateRuntime();
    //excute 
            dynamic scope = runtime.ExecuteFile(@"Calculator.py");
    //call the python method
            Console.WriteLine("Sum={0}", scope.add(1, 2));
            Console.ReadLine();
        }
    }
}

How to submit(Post) a webfrom from python/IronPython

In this post,I am going to show you how to post data from python to a webfrom from python.
import urllib.parse
import urllib.request
url='http://www.dijksterhuis.org/test/post.php'
values={'keyword':'Void',
        'data':'aspdotnetcodebook'
        }
data=urllib.parse.urlencode(values)
binary_data = data.encode('utf-8')
req=urllib.request.Request(url,binary_data)
response=urllib.request.urlopen(req)
the_page=response.read()
print (the_page)