英語をすらすら読める人はここを読めば全て解決する。 code.msdn.microsoft.com
C#からPythonを呼び出し、返り値を取得する方法としては、C#におけるプロセス間通信の一つである Process
を使って、Pythonのスクリプトを実行し、その標準出力(コンソール出力)をストリームで受け取るという方法が最も現実的だろう。
Python側ではmainに相当する部分と戻り値を渡すための print
文を書いておく必要がある。
Pythonの関数の戻り値そのものを取得できるわけではないので、ある関数だけ実行するということはできないし、想定していない標準出力には対応できない。
以下は、上記のURLのサンプル例を自分なりに修正したもの。
Program.cs
using System; using System.Diagnostics; using System.IO; namespace ConsoleApp4_python { class Program { static void Main(string[] args) { //下記のPythonスクリプトへのファイルパスを記述する string myPythonApp = "test.py"; int x = 2; int y = 5; var myProcess = new Process { StartInfo = new ProcessStartInfo("python.exe") { UseShellExecute = false, RedirectStandardOutput = true, Arguments = myPythonApp + " " + x + " " + y } }; myProcess.Start(); StreamReader myStreamReader = myProcess.StandardOutput; string myString = myStreamReader.ReadLine(); myProcess.WaitForExit(); myProcess.Close(); Console.WriteLine("Value received from script: " + myString); } } }
test.py
として以下のように書く。
import sys x = int(sys.argv[1]) y = int(sys.argv[2]) print(x + y)
簡略化のため if __name__ == '__main__':
は省略してあるが、あっても良い。
Pythonのファイルは、C#の実行時の作業フォルダと同じ場所に置き、Visual Studio等でコンパイルするなどして実行したら次のように表示されるだろう。
Value received from script: 7
フォルダ構成例と、Visual Studio用コマンドプロンプトから C#をコンパイルするための csc Program.cs
を実行して Program.exe
を作成し、実行してみた例を以下に示す。