IronPython w / C# – 如何读取Python变量的值
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了IronPython w / C# – 如何读取Python变量的值,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2066字,纯文字阅读大概需要3分钟。
内容图文
![IronPython w / C# – 如何读取Python变量的值](/upload/InfoBanner/zyjiaocheng/824/a6d8782eed494838ad54e0d1eb59f3b9.jpg)
我有两个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");
内容总结
以上是互联网集市为您收集整理的IronPython w / C# – 如何读取Python变量的值全部内容,希望文章能够帮你解决IronPython w / C# – 如何读取Python变量的值所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。