IronPython w/ C# - 如何读取 Python 变量的值

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

我有两个 python 文件:mainfile.py 和 subfile.py

mainfile.py 依赖于 subfile.py.

中的某些类型

mainfile.py 看起来像这样。

from subfile import *
my_variable = [1,2,3,4,5]

def do_something_with_subfile
   #Do something with things in the subfile.
   #Return something.

我正在尝试在 C# 中加载 mainfile.py 并获取 my_varaible 的值,但我在寻找充分描述方法之间关系的资源时遇到了一些困难打电话给我,诚然,我对 Python.

知之甚少

这是我写的:

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);

//A couple of files.
var mainfile = @"C:\ACodeFolder\mainfile.py";
var subfile = @"C:\ACodeFolder\subfile.py";

var scope = engine.CreateScope();

var scriptSource = engine.CreateScriptSourceFromFile(subfile);
var compiledScript = scriptSource.Compile();
compiledScript.Execute(scope);

scriptSource = engine.CreateScriptSourceFromFile(mainfile);
compiledScript = scriptSource.Compile();
compiledScript.Execute(scope);

scriptSource = engine.CreateScriptSourceFromString("my_variable");
scriptSource.Compile();
var theValue = compiledScript.Execute(scope);

但是执行时,theValue 为空。

我真的不知道我在做什么。所以真正的问题是:

如何从 mainfile.py 读取 my_variable 的值?顺便说一句,对于 Python 命名空间中可用的方法以及如何在 C# 和 Python 之间真正交互,是否有很好的介绍性资源?

进一步挖掘后,我发现了一篇文章和一个有用的 Whosebug 问题。

SO: IronPython Integration in C#

MSDN Blog: Hosting IronPython in C#

最终对我有用的代码是:

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".

实际上有一种更简单的方法,使用 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");