Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

C#(.NET 5)からPython3の引数つきスクリプトを呼び出す

最近流行りのプロジェクトはnodeやpythonのリファ実装が充実していたりします
ところが、それと連携したいプロジェクトはC#で書かれており、できれば更新はしたくない……
そういうときは、いっそC#のほうからpythonを読み出すというのも考えていいかも

実際のところ

using System; 
using System.IO; 
using System.Diagnostics; 

namespace CallPython 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            // Pythonのコマンド コマンドラインで通るなら、フルパスでなくていい
            string python = @"python3.exe"; 


            // 実行するスクリプトと引数
            string myPythonApp = "sum.py"; 
            int x = 2; 
            int y = 5; 

            // プロセスのオブジェクトを作成
            ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python); 

            // 標準出力から結果を取得するための設定 
            myProcessStartInfo.UseShellExecute = false; 
            myProcessStartInfo.RedirectStandardOutput = true; 

            // スクリプトと引数をコマンド文字列として渡す
            myProcessStartInfo.Arguments = myPythonApp + " " + x + " " + y; ; 

            Process myProcess = new Process(); 
            // 先ほど作成したオブジェクトを新造プロセスに紐づけ、起動
            myProcess.StartInfo = myProcessStartInfo; 
            myProcess.Start(); 

            // 標準出力の結果をストリームに流し込み、文字列として固める 
            StreamReader myStreamReader = myProcess.StandardOutput; 
            string myString = myStreamReader.ReadLine(); 

            // お行儀よくとじる
            myProcess.WaitForExit(); 
            myProcess.Close(); 

            // 固めた文字列を出力する 
            Console.WriteLine("Value received from script: " + myString); 

        } 
    }
}

一方のpython

import sys
import json

val_a = sys.argv[ 1 ]
val_b = sys.argv[ 2 ]

print( json.dumps( { 'val_a' : int(val_a) , 'val_b' : int(val_b) } ) )

実行すると

> dotnet run
Value received from script: {"val_a": 2, "val_b": 5}