Passing DataTable to IronPython
Asked Answered
R

1

5

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?

Redwood answered 5/12, 2012 at 16:53 Comment(0)
R
10

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.

Reformer answered 5/12, 2012 at 17:2 Comment(1)
Do not feel silly at all. Being python not-compiled, it's very easy to make this kind of simple mistakes...Reformer

© 2022 - 2024 — McMap. All rights reserved.