calling python.py from C# .net

爷,独闯天下 提交于 2021-02-08 08:16:51

问题


I have a problem in calling a python script from C#. My python script computes a value based on param 1 and param 2 and sends the computed value. I am not able to get the computed value. say, for example I am taking a simple python class and calling for C#

the below is 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)

below is the C# code to call it.

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();

Since 2,3 are sent to main () in python, I want '5'back. I do not know how to get it back. Please help


回答1:


The following code snippet worked for me : C# code to call Python

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);

        }
    }

}

and following Python Code which takes two inputs and returns the sum of those:

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))


来源:https://stackoverflow.com/questions/52402239/calling-python-py-from-c-sharp-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!