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')
routesArray.append(route)
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"};
engine.SetSearchPaths(lPath);
ScriptRuntime scripting = engine.Runtime;
dynamic runtime = scripting.UseFile(strPy);
dynamic routes = runtime.getRoutes();
foreach(dynamic route in routes)
{
Console.WriteLine(route.depart + " -> " + route.arrive);
}
Console.Read();
}
}
}
Useful?
Categories: Uncategorized
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”
self.response.out.write(”)
for m in re.finditer(strRouteRegex, html):
self.response.out.write(”)
self.response.out.write(”)
def main():
application = webapp.WSGIApplication([(‘/’, MainHandler)],
debug=True)
util.run_wsgi_app(application)
if __name__ == ‘__main__’:
main()
LikeLike
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; ?
Thx.
LikeLike