我有两个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.
Run Code Online (Sandbox Code Playgroud)
我正在尝试在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);
Run Code Online (Sandbox Code Playgroud)
但是当执行时,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");
Run Code Online (Sandbox Code Playgroud)
经过进一步挖掘,我发现了一篇很有帮助的文章和 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".
Run Code Online (Sandbox Code Playgroud)