英語をすらすら読める人はここを読めば全て解決する。 code.msdn.microsoft.com
方法としては、C#におけるプロセス間通信の一つである Process を使って、pythonのスクリプトを実行し、その標準出力(コンソール出力)をストリームで受け取るという方法。pythonの戻り値そのものを取得できるわけではないので、ある関数だけ叩くということはできず、python側ではmainに相当する部分と戻り値に相当するprint文を書いておく必要がある。以下は、上記のURLのサンプル例を自分なりに修正したもの。
Program.cs
using System; using System.Diagnostics; using System.IO; namespace ConsoleApp4_python { class Program { static void Main(string[] args) { string myPythonApp = @"C:\Users\Masahiro\source\repos\project\interprocess\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)
実行したら次のようになる
Value received from script: 7