托管的IronPython:导入包含自定义函数的文件 [英] Hosted IronPython: import files which contain custom functions
问题描述
情况
托管的IronPython允许开发人员将参数设置为脚本.每次创建IPy引擎对象时,我都会设置一个这样的参数(ParamName),但是当我尝试导入使用我的自定义参数的python模块时,却收到异常消息,消息全局名称'ParamName'不是定义".
Hosted IronPython allows developers to set parameters into script. Every time when a IPy engine object is created, I set such a parameter (ParamName), but when I try to import python module, in which my custom parameter is used, I get an exception with message "global name 'ParamName' is not defined".
代码示例
class PythonScriptingEngine
{
private ScriptEngine pyEngine;
private ScriptScope pyScope;
public PythonScriptingEngine()
{
pyEngine = Python.CreateEngine();
pyScope = pyEngine.CreateScope();
}
public object Run(string script)
{
ScriptSource source = pyEngine.CreateScriptSourceFromString(script);
CompiledCode compiled = source.Compile();
return compiled.Execute(pyScope);
}
public void SetParameter(string name, int value)
{
pyScope.SetVariable(name, value);
}
}
// execution
var engine = new PythonScriptingEngine();
engine.SetParameter("ParamName", 10);
engine.Run(@"import SampleScriptWithParamName");
问题
有没有解决此情况的方法?如何导入使用自定义参数的python脚本?
Is there any workaround to this situation? How can I import python script in which custom parameter is used?
推荐答案
正如Simon所指出的,问题在于ParamName
不在SampleScriptWithParamName
的范围内.一种实现方法是将其添加到内置变量集中,如下所示:
As Simon pointed out, the issue is that ParamName
is not in scope for SampleScriptWithParamName
. One way to achieve that is to add it to the set of builtin variables like so:
public void SetParameter(string name, int value)
{
pyEngine.GetBuiltinModule().SetVariable(name, value);
}
这应该使它在任何地方都可以使用,但是我现在无法对其进行测试.
This should make it available everywhere, but I don't have the ability to test it right now.
这篇关于托管的IronPython:导入包含自定义函数的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!