如何从silverlight 5执行ironpython脚本文件?

时间:2014-03-04 17:52:20

标签: ironpython silverlight-5.0

我正在尝试在silverlight中执行ironpython脚本文件,但我得到了异常

  

序列不包含匹配元素

string importScript = "import sys" + Environment.NewLine +
        "sys.path.append( r\"{0}\" )" + Environment.NewLine +
        "from {1} import *";

        // python script to load
        string fullPath = @"c:\path\myModule.py";

        var engine = Python.CreateEngine();
        ScriptScope scope = engine.CreateScope();

        // import the module

        string scriptStr = string.Format(importScript,Path.GetDirectoryName(fullPath),Path.GetFileNameWithoutExtension(fullPath));
        var importSrc = engine.CreateScriptSourceFromString(scriptStr, Microsoft.Scripting.SourceCodeKind.File);
        importSrc.Execute(scope);

        // now you ca execute one-line expressions on the scope e.g.
        string expr = "functionOfMyModule()";
        var result = engine.Execute(expr, scope);`

1 个答案:

答案 0 :(得分:0)

首先在这里创建范围......像这样

public static ScriptScope GetModule()
    {
        var pyfile = "PythonFunction.py";
        ScriptEngine engine = new ScriptRuntime(DynamicEngine.CreateRuntimeSetup(true)).GetEngine("IronPython");
        var code = new XapVirtualFilesystem().GetFileContents(pyfile);
        ScriptScope scope = engine.CreateScope();
        ScriptSource script = engine.CreateScriptSourceFromString(code, pyfile);
        script.Execute(scope);
        return scope;
    }

在您想要的地方调用此方法

python文件遵循PythonFunction.py

import clr clr.AddReference( “System.Windows”) 从System.Windows导入应用程序

STR = Application.Current.RootVisual.FindName( “TextBox2中”)。文本

def hello(str):    打印“你好”+ str +“!欢迎来到IronPython!”    返回“Somthing form iron Python”

Application.Current.RootVisual.FindName("textBox1").Text=hello(Application.Current.RootVisual.FindName("textBox2").Text)