Setting and getting variables in .Net hosted IronPython script

♀尐吖头ヾ 提交于 2019-12-04 10:48:52

Here is the way I would provide script with a variable and pick the results afterwards:

        var engine = Python.CreateEngine();
        var scope = engine.CreateScope();
        scope.SetVariable("foo", 42);
        engine.Execute("print foo; bar=foo+11", scope);
        Console.WriteLine(scope.GetVariable("bar"));

To add onto Pawal's answer, the variables set in this manner are not "global" and can't be accessed by imported functions. I learned from here, that this is how to make them global and accessible by all:

var engine = Python.CreateEngine();
engine.GetBuiltinModule().SetVariable("foo", 42);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!