[英]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为null。
我真的不知道我在做什么。 因此,真正的问题是:
如何从mainfile.py中读取my_variable的值? 切线地,Python命名空间中的方法是否有很好的入门资源,以及如何在C#和Python之间真正进行交互?
使用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");
经过一些进一步的挖掘后,我发现了一篇文章和一个有帮助的StackOverflow问题。
最终对我有用的代码是:
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".
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.