IronPython w/ C# - How to Read Values of Python Variables

最后都变了- 提交于 2019-12-03 15:15:13

There's actually a simpler way to do it, using ScriptScope.GetVariable:

var engine = Python.CreateEngine();
//Set up the folder with my code and the folder with struct.py.
var searchPaths = engine.GetSearchPaths();
searchPaths.Add(@"C:\ACodeFolder");
searchPaths.Add(@"C:\tools\python\lib");
engine.SetSearchPaths(searchPaths);

var mainfile = @"C:\ACodeFolder\mainfile.py";
var scope = engine.CreateScope();
engine.CreateScriptSourceFromFile(mainfile).Execute(scope);

var result = scope.GetVariable("my_variable");
//"result" now contains the value of my_variable.
// or, attempt to cast it to a specific type
var g_result = scope.GetVariable<int>("my_variable");
Anthony Compton

After some more digging, I uncovered an article and a StackOverflow question that was helpful.

SO: IronPython Integration in C#

MSDN Blog: Hosting IronPython in C#

The code that finally worked for me is:

var engine = Python.CreateEngine();
//Set up the folder with my code and the folder with struct.py.
var searchPaths = engine.GetSearchPaths();
searchPaths.Add(@"C:\ACodeFolder");
searchPaths.Add(@"C:\tools\python\lib");
engine.SetSearchPaths(searchPaths);

var mainfile = @"C:\ACodeFolder\mainfile.py";
var scope = engine.CreateScope();
engine.CreateScriptSourceFromFile(mainfile).Execute(scope);

var expression = "my_variable";
var result = engine.Execute(expression, scope);
//"result" now contains the value of my_variable".
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!