Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing DataTable to IronPython

I have a .NET project where I am using IronPython to perform some processing of the data. At present, the C# code loops through and generates an IronPython script for each row and column that requires dynamic calculation. However, I'd like to make the process more efficient by passing in the DataTable object and a script to execute against it. Unfortunately, I'm getting 'DataTable' object is unsubscriptable error and no processing takes place.

C# snippet to generate and execute IronPython script:

DataTable dt = new DataTable();
dt.Columns.Add("count", typeof(int));
dt.Columns.Add("calc", typeof(int));
dt.Rows.Add(1, null);

ScriptEngine engine = Python.CreateEngine(options);
ScriptScope scope = engine.CreateScope();
scope.SetVariable("dt", dt);
ScriptSource source = engine.CreateScriptSourceFromString(code, SourceCodeKind.AutoDetect);
object result = source.Execute(scope);
DataTable table = scope.GetVariable<System.Data.DataTable>("dt");

Python script to be executed against the table:

import clr
clr.AddReference('System.Data')
from System import Data
from System.Data import DataTable
for row in dt.Rows:
    dt["calc"] = dt["count"] + 1

How do I fix the 'DataTable' object is unsubscriptable error, or is there a better way to handle passing a DataTable into IronPython?

like image 717
saluce Avatar asked Dec 05 '12 16:12

saluce


1 Answers

DataTable object really is unsubscriptable, i.e. cannot be accessed through indexed properties (i.e. dt[index] ).

You probably meant this:

for row in dt.Rows:
    row["calc"] = row["count"] + 1

where I replaced dt variable with row.

like image 167
digEmAll Avatar answered Oct 03 '22 08:10

digEmAll