从C#.net调用python.py

时间:2018-09-19 09:12:47

标签: c# python process

从C#调用python脚本时遇到问题。我的python脚本基于参数1和参数2计算一个值,然后发送计算出的值。我无法获得计算值。例如,我正在学习一个简单的python类并要求使用C#

下面是python.py:

import argparse
class demo:

  def add(self,a,b):
     return a+b

def main(a,b):
 obj=demo()
 value=obj.add(a,b)
 print(value)
 return value

if __name__ == "__main__":
arg_parse = argparse.ArgumentParser()
arg_parse.add_argument("a")
arguments = arg_parse.parse_args()
main(arguments.a,3)

下面是要调用它的C#代码。

Process p = new Process(); 
        int a = 2;
        p.StartInfo.FileName = "C:\\Users\\xyx\\AppData\\Local\\Programs\\Python\\Python36-32\\pythonw\\python.exe";
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.UseShellExecute = false; 
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.CreateNoWindow = true;
        p.StartInfo.Arguments = "C:\\Users\\xyx\\AppData\\Local\\Programs\\Python\\Python36-32\\pythonw\\python.py "+a; parameter
        p.Start(); 
        StreamReader s = p.StandardOutput;
        standardError = s.ReadToEnd();
        output = s.ReadToEnd().Replace(Environment.NewLine, string.Empty); 

        p.WaitForExit();

由于在Python中将2,3发送到main(),我希望返回“ 5”。我不知道该如何找回。请帮助

1 个答案:

答案 0 :(得分:1)

以下代码段对我有用:调用Python的C#代码

using System;
using System.Diagnostics;
using System.IO;
namespace ScriptInterface
{
    public class ScriptRunner
    {
        //args separated by spaces
        public static string RunFromCmd(string rCodeFilePath, string args)
        {
            string file = rCodeFilePath;
            string result = string.Empty;

            try
            {

                var info = new ProcessStartInfo(@"C:\Users\xyz\AppData\Local\Programs\Python\Python37\python.exe");
                info.Arguments = rCodeFilePath + " " + args;

                info.RedirectStandardInput = false;
                info.RedirectStandardOutput = true;
                info.UseShellExecute = false;
                info.CreateNoWindow = true;

                using (var proc = new Process())
                {
                    proc.StartInfo = info;
                    proc.Start();
                    proc.WaitForExit();
                    if (proc.ExitCode == 0)
                    {
                        result = proc.StandardOutput.ReadToEnd();
                    }                    
                }
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception("R Script failed: " + result, ex);
            }
        }
        public static void Main()
        {
            string args = "1 2";
            string res = ScriptRunner.RunFromCmd(@"your file path", args);

        }
    }

}

以及后面的Python代码,该代码接受两个输入并返回这些输入的总和:

import sys
def add_numbers(x,y):
   sum = x + y
   return sum

num1 = int(sys.argv[1])
num2 = int(sys.argv[2])

print(add_numbers(num1, num2))