問題描述:使用C#調用下面的帶參數的用python寫的方法,並且想要獲取返回值。
def Quadratic_Equations(a,b,c): D=b**2-4*a*c ans=[] ans.append((-b+math.sqrt(D))/(2*a)) ans.append((-b-math.sqrt(D))/(2*a)) return ans
C#代碼如下:
class Program { static void Main(string[] args) { string name = "CallPythonExam.py"; List<string> param = new List<string>() { "3", "5", "1" }; RunPythonScript(name, param); } static void RunPythonScript(string name, List<string> args) { Process p = new Process(); // .py文件的絕對路徑 string path = @"D:\PythonPrograms\VelocityProfile\VelocityProfile\" + name; string arguments = path; // 添加參數 foreach (var item in args) arguments += " " + item; // python安裝路徑 p.StartInfo.FileName = @"C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\python.exe"; // 下面這些是我直接從網上抄下來的....... p.StartInfo.Arguments = arguments; // 不啟用shell啟動進程 p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardError = true; // 不創建新窗口 p.StartInfo.CreateNoWindow = true; p.Start(); StreamReader sr = p.StandardOutput; while (!sr.EndOfStream) Console.WriteLine(sr.ReadLine()); Console.ReadLine(); p.WaitForExit(); } }
python代碼如下:
import math import sys def Quadratic_Equations(stra,strb,strc): a=float(stra) b=float(strb) c=float(strc) D=b**2-4*a*c ans=[] ans.append((-b+math.sqrt(D))/(2*a)) ans.append((-b-math.sqrt(D))/(2*a)) print(ans[0]) print(ans[1]) #return str(ans[0]) Quadratic_Equations(sys.argv[1],sys.argv[2],sys.argv[3])
這樣就可以在屏幕上輸出方程的解。