C#


IronPythonをC#から利用

今回はC#からIronPythonを使ってみたいと思います。 例としてIronPythonの簡単なCUIベースの実行環境を作ります。
仕様は、入力した文字のセーブぐらいはでき、エラーも表示するよう簡単なものとします。 これがあると少しだけ便利です。
今回のプログラムをコンパイルするにはIronPythonをインストールしていなければなりません(必要なdllがあればそれでいいです)。 ビルド時にIronPython.dllをリンクするのを忘れないようにしましょう。
では、コードを示します。

001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057 058

//2009/09/x Shirao //IronPython簡易実行環境 using IronPython.Hosting; using System; class UseCsIpy { public static void Main() { String all_input = ""; PythonEngine engine = new PythonEngine(); Console.WriteLine("TIPC -IronPython簡易実行環境- v0.0.1"); Console.WriteLine("終了:exit か END, セーブ __save ファイル名"); while (true) { Console.Write(">"); string input = Console.ReadLine(); if (input == "END" || input == "exit") break; if (input == "__save") input += " "; if (input.IndexOf("__save ") == 0) { input = input.Replace("__save ", ""); if (input == "") input = "temp.py"; try { System.IO.StreamWriter file = new System.IO.StreamWriter(input); file.WriteLine(all_input); file.Close(); } catch (Exception e) { Console.WriteLine(e.Message); } continue; } if (input[input.Length - 1] == ':') { while (true) { Console.Write("::"); string temp = Console.ReadLine(); if (temp == "") break; input += "\n" + temp; } } try { engine.Execute(input); all_input += input+"\n"; } catch (Exception exc) { Console.WriteLine("ERROR : "+exc.Message); } } engine.Shutdown(); } }

ポイント

PythonEngine

PythonEngineはIronPyhtonの実行エンジンです。このクラスのインスタンス をつかってIronPythonを間接的に利用します。

Execute

コードの実行にはこのメソッドを使います。引数にはPythonの命令文字列を指定します。 ただし、関数の定義やループ処理はまとめて突っ込まないといけません。そのための処理が行36から45の処理です。 これは:で終わっていたら空行が入力されるまで読み取る簡単な処理で、本当はもっとまじめにしたほうがいいのですが 適当にするならこんなものでもいいと思います。

036 037 038 039 040 041 042 043 044 045

if (input[input.Length - 1] == ':') { while (true) { Console.Write("::"); string temp = Console.ReadLine(); if (temp == "") break; input += "\n" + temp; } }

Shutdown

これでIronPython実行エンジンを停止します。

保存

保存は、__save hoge.pyの形式で 行うこととしました。セーブかどうかの判断をしているのが行21です。これは、入力文字列が__saveで 始まっていたら(IndexOfの結果が0なら)セーブとみなします。
セーブするファイル名はReplaceを使って得ています。無名ならtemp.pyにセーブします。 なお、行19のif文は処理を一元化するためのものです。
ファイル名が決まれば、後は記憶しておいた入力文字列を書き込むだけです。この処理は行26から28で行っています。

019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035

if (input == "__save") input += " "; if (input.IndexOf("__save ") == 0) { input = input.Replace("__save ", ""); if (input == "") input = "temp.py"; try { System.IO.StreamWriter file = new System.IO.StreamWriter(input); file.WriteLine(all_input); file.Close(); } catch (Exception e) { Console.WriteLine(e.Message); } continue; }

付録

実行画面

参考に、実行画面を示しましょう。ここでは、IronPythonを使って、 メッセージボックスを表示しています。

ソース・実行ファイル

C#ソースコードと実行ファイルを置いておきます。


プログラムに戻る