C# から IronPython を実行する

IronPython を試した事が無かったので、超簡単なサンプルを作ってみました。IronPython だけ使っては芸がないので、C# からスクリプトを呼び出すようにしています。その代わり Python スクリプトは手抜き。

Python
print('Sample.py Called')

message = 'Hello, IronPython'
C#
using System;
using System.Reflection;
using System.IO;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
namespace PythonSample
{
    class Program
    {
        static void Main(string[] args)
        {
            // スクリプトファイルのパスを求める
            Assembly assembly = typeof(Program).Assembly;
            string dirPath = Path.Combine(Path.GetDirectoryName(assembly.Location), "Scripts");
            string filePath = Path.Combine(dirPath, "Sample.py");

            // Python スクリプトエンジン生成
            ScriptEngine engine = Python.CreateEngine();

            // Python スクリプトを読み込む
            ScriptSource source = engine.CreateScriptSourceFromFile(filePath);

            // スコープ生成
            // IronPython に変数を渡したり、
            // 逆に取得したりするときに使う。
            ScriptScope scope = engine.CreateScope();

            // Python スクリプト実行
            source.Execute(scope);

            // 実行結果を取得
            string result = scope.GetVariable<string>("message");

            // 結果出力
            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}
実行結果

f:id:griefworker:20090909215037p:image

実行時にスクリプトファイルを探すように作れば、スクリプトファイルを追加しても再ビルド不要ですね。

IronPython を使えば、拡張可能なアプリが手軽に作れそう。