Passing DataTable to IronPython

左心房为你撑大大i 提交于 2019-12-23 12:26:24

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/13728305/passing-datatable-to-ironpython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!