2

私は次のコードを持っています(ただのテスト):

var engine = Python.CreateEngine();
var runtime = engine.Runtime;

    try
    {                
        dynamic test = runtime.UseFile(@"d:\test.py");

        test.SetVariable("y", 4);
        test.SetVariable("client", UISession.ControllerClient);
        test.Simple();
    }
    catch (Exception ex)
    {
        var eo = engine.GetService<ExceptionOperations>();
        Console.WriteLine(eo.FormatException(ex));
    }

しかし、代わりに文字列からスクリプトをロードしたいと思います。

4

2 に答える 2

8

を使用engine.CreateScriptSourceFromStringして、ファイルではなく文字列からスクリプトをスコープにロードできます。

     StringBuilder sb = new StringBuilder();
     sb.Append("def helloworld():\r\n");
     sb.Append("    print \"hello world\"\r\n");
     string code = sb.ToString();
     ScriptEngine engine = Python.CreateEngine();         
     ScriptSource source = engine.CreateScriptSourceFromString(code, SourceCodeKind.File);
     ScriptScope scope = engine.CreateScope();
     source.Execute(scope);
     Func<object> func = scope.GetVariable<Func<object>>("helloworld");
     Console.WriteLine(func());
于 2010-01-28T16:15:51.357 に答える
3

IronPython Cookbook のこの例は役に立ちますか? これは、C# から Python クラス メソッドを呼び出す方法に関するものですが、ファイルからスクリプトをロードする実際の例も含まれています。この例は IronPython 2.6 で動作します (ホスティングがかなり変更されているため、バージョンに注意する必要があります)。

http://www.ironpython.info/index.php/Using_Python_Classes_from_.NET/CSharp_IP_2.6

于 2010-01-28T16:15:04.667 に答える