标签:c ironpython
我有两个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");
标签:c,ironpython 来源: https://codeday.me/bug/20190519/1137734.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。