0%

C# 與 python 的參數傳遞

C# 與 python 的參數傳遞

C# 與 python 的參數傳遞

前言

假如目前有項需求,需要用 C# 處理,但是還另外有複雜的 DL 運算需要透過 python 去跑,如果程式都是在同一台機器上執行,目前自己找到的解決方式,就是用 C# 去執行 python.exe 同時接收運算結果,詳述如下。

python 端程式

模擬情境是 負責運算的 python 程式為 returnDemo.py 運算前會接到一個 ‘123’ 的參數

1
2
3
4
5
6
7
def returnDemo(guid):    
processed_guid = 'abc' + guid
print(processed_guid)

import sys
guid = sys.argv[1]
returnDemo(guid)

此時先用 cmd 測試 python程式可正常運作。

1
C:\ProgramData\Anaconda3\python.exe R:\returnDemo.py '123'

returnDemopy

C# 端程式

這邊是找到網路上的文章 Running Python Script From C# and Working With the Results 做為參考並加以改寫。
改寫後的程式如下,主程式會有三個參數

  1. 欲執行 py 的 python 程式路徑
  2. 欲執行的 py 路徑
  3. py 程式執行時所需要的參數 (本例是 ‘123’ )
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    public static string run_cmd(string python, string cmd, string args)
    {
    ProcessStartInfo start = new ProcessStartInfo();
    start.FileName = python;
    start.Arguments = string.Format("\"{0}\" \"{1}\"", cmd, args);
    start.UseShellExecute = false;// Do not use OS shell
    start.CreateNoWindow = true; // We don't need new window
    start.RedirectStandardOutput = true;// Any output, generated by application will be redirected back
    start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions)
    using (Process process = Process.Start(start))
    {
    using (StreamReader reader = process.StandardOutput)
    {
    string stderr = process.StandardError.ReadToEnd(); // Here are the exceptions from our Python script
    string result = reader.ReadToEnd(); // Here is the result of StdOut(for example: print "test")
    return result;
    }
    }
    }

    static void Main(string[] args)
    {
    string s = run_cmd(@"C:\ProgramData\Anaconda3\python.exe", @"R:\returnDemo.py", "'123'");
    Console.WriteLine(s);
    }
    cs

透過這樣的方法,一般的需求就可用 C# 處理,複雜的 DL 運算可交由 python 負責,可處理 keras 深度學習等高階元件運算。