由C#程式代為執行以下命令 python.exe main.py var1 var2
main.py是python的主要程式碼, 由外部指令傳入兩個參數var1與var2做相乘開根號的運算
main.py的程式碼如下:
#main.py
import numpy as np
import multi
import sys
def func(a,b):
result=np.sqrt(multi.multiplication(int(a),int(b)))
# result = a * b
return result
#x = func
#print(x(3,5))
if __name__ == '__main__':
print(func(sys.argv[1],sys.argv[2]))
C#程式碼如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string filePythonExePath;
/// <summary>
/// ML Sharp Python class constructor
/// </summary>
/// <param name="exePythonPath">Python EXE file path</param>
public void MLSharpPython(string exePythonPath)
{
filePythonExePath = exePythonPath;
}
/// <summary>
/// Execute Python script file
/// </summary>
/// <param name="filePythonScript">Python script file and input parameter(s)</param>
/// <param name="standardError">Output standard error</param>
/// <returns>Output text result</returns>
public string ExecutePythonScript(string filePythonScript, out string standardError)
{
string outputText = string.Empty;
standardError = string.Empty;
try
{
using (Process process = new Process())
{
process.StartInfo = new ProcessStartInfo(filePythonExePath)
{
Arguments = (filePythonScript + " 3 3"),
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
process.Start();
outputText = process.StandardOutput.ReadToEnd();
outputText = outputText.Replace(Environment.NewLine, string.Empty);
standardError = process.StandardError.ReadToEnd();
process.WaitForExit();
}
}
catch (Exception ex)
{
string exceptionMessage = ex.Message;
}
return outputText;
}
private void button3_Click(object sender, EventArgs e)
{
string err;
string outResult;
// _writer = new ListBoxWriter(listBox1); // DebugWin is the name og my listbox
// Console.SetOut(_writer);
listBox1.Items.Add("Button 3");
MLSharpPython(@"D:\_APP\Anaconda3\python.exe");
outResult = ExecutePythonScript(@"d:\main.py", out err);
textBox3.AppendText("Result= " + outResult + "\n");
textBox3.AppendText("Error= " + err + "\n");
textBox3.ScrollToCaret();
}
}
}
參考:
■介紹使用C#呼叫Python語法, 應用於影像處理及機器學習的程式架構 (Using C# to run Python Scripts with Machine Learning Models )
https://medium.com/@ernest.bonat/using-c-to-run-python-scripts-with-machine-learning-models-a82cff74b027
■C#呼叫Python的四種方法
https://www.itread01.com/content/1545323704.html
■MSDN - Process.BeginOutputReadLine Method