Posts

Showing posts with the label IronPython

IronPython, PetaPoco, and .Net 4 'dynamic'

Recently I was playing around with IronPython and PetaPoco (a .Net micro-ORM). PetaPoco allows the use of the 'dynamic' keyword when querying data. Unfortunately, the dynamic keyword is not available in IronPython. However, since IronPython makes use of the DLR, its types are already dynamic instances. Therefore, all I needed to do was provide a Python type instead of the dynamic keyword (I used 'object'). The end result is an interesting combination of Oracle, PetaPoco, .Net 4, and IronPython. import clr import csv clr.AddReferenceToFile( "Oracle.DataAccess.dll" ) clr.AddReferenceToFile( "PetaPoco.dll" ) import Oracle.DataAccess.Client import PetaPoco conString = "user id=USER;data source=DB;password=PASS" provider = Oracle.DataAccess.Client.OracleClientFactory() db = PetaPoco.Database(conString, provider) query = "select * from my_table" result = db.Fetch[object](query) csvFile = csv.writer(open('out.csv', ...

Embedding IronPython Within C#

IronPython is a Python implementation that runs on the .Net DLR and allows the use of the powerful .Net Framework from Python. While this is very exciting for Python development, there are also great advantages for other .Net languages. Using IronPython, we can run Python code from without a .Net application. More specifically, we can allow a .Net application to be extendable or scriptable with python. In the following example, I will create a basic python 'plugin' framework in C#. Python Code class TestClass(object): def __init__(self): self.A = 5 self.B = 4 def Go(self): return self.A + self.B C# Code public static object Execute(string code) { object result; try { ScriptEngine engine = Python.CreateEngine(); ScriptScope scope = engine.CreateScope(); ScriptSource source = engine.CreateScriptSourceFromString(code); source.Execute(scope); object t = scope.GetVariable("TestClass"); object o = engine.Operatio...