C#调用带参数的python脚本

问题描述:使用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])

这样就可以在屏幕上输出方程的解。

https://github.com/Larissa1990/use-C-to-call-.py-file

猜你喜欢

转载自www.cnblogs.com/larissa-0464/p/11965564.html