首页 > 编程语言 > 详细

C#调用带参数的python脚本

时间:2019-12-01 13:05:43      阅读:117      评论:0      收藏:0      [点我收藏+]

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

C#调用带参数的python脚本

原文:https://www.cnblogs.com/larissa-0464/p/11965564.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!