Home > Uncategorized > Calling Python from C#

Calling Python from C#

Here is a simple example of how to call an IronPython function from C#

Here is the PY file: (With URL & Regex removed)

import urllib2
import re
import array

def getRoutes():
    strRouteRegex = '(?<From>[A-Z]{3})...\d+..iata...=..(?<To>[A-Z]{3})'
    httpRequest = urllib2.urlopen("http://www.somewebsite.com/")
    html = httpRequest.read()
    routesArray = []
    for m in re.finditer(strRouteRegex, html):
        route = FlightRoute()
        route.depart = m.group('From')
        route.arrive = m.group('To')
    return routesArray;

class FlightRoute:
    depart = ''
    arrive = ''

And here is the C# calling code – This requires the .NET 4 to handle the dynamic types.

using System;
using System.Collections.Generic;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

namespace CSPY
    class Program
        static void Main(string[] args)
            const string strPy = @"C:\research\Program.py";
            ScriptEngine engine = Python.CreateEngine();
            var lPath = new List<string> {@"c:\Program Files\IronPython 2.7\Lib"};
            ScriptRuntime scripting = engine.Runtime;
            dynamic runtime = scripting.UseFile(strPy);
            dynamic routes = runtime.getRoutes();
            foreach(dynamic route in routes)
                Console.WriteLine(route.depart + " -> " + route.arrive);
Categories: Uncategorized
  1. May 13, 2011 at 2:49 pm

    Here is the Google AppEngne version of the above code:

    from google.appengine.ext import webapp
    from google.appengine.ext.webapp import util

    import urllib2
    import re
    import array

    class MainHandler(webapp.RequestHandler):
    def get(self):
    strRouteRegex = ‘airports..([A-Z]{3})…\d+…iata…=..([A-Z]{3})’
    httpRequest = urllib2.urlopen(“http://www.flygermania.de/”)
    html = httpRequest.read()
    self.response.headers[“Content-Type”] = “text/xml”
    for m in re.finditer(strRouteRegex, html):

    def main():
    application = webapp.WSGIApplication([(‘/’, MainHandler)],

    if __name__ == ‘__main__’:


  2. ssx
    July 10, 2012 at 12:46 am

    I’m using Eclipse, could someone explain how to add references to the assemblies which will permit me to use using IronPython.Hosting; and using Microsoft.Scripting.Hosting; ?


  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: