2

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

swifty
  • 165
  • 1
  • 1
  • 17

1 Answers1

3

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))
Apoorva Raju
  • 300
  • 1
  • 14
  • i get proc.ExitCode=2 and not 0 – swifty Sep 19 '18 at 12:11
  • Does the python code work outside C# code ? I meant in command prompt ? Issue might be with python script – Apoorva Raju Sep 19 '18 at 12:59
  • Yes. It executes properly otherwise. I also tried copy-pasting Ur code above. Same behaviour. It does not throw exception . It never enters if( proc.exitcode==0) – swifty Sep 19 '18 at 17:08
  • Strange , did you change the path of Python.exe ?? i had python37 on my system . – Apoorva Raju Sep 19 '18 at 17:42
  • I got >>> import sys >>> print(sys.executable) C:\Users\xyx\AppData\Local\Programs\Python\Python36-32\pythonw.exe – swifty Sep 20 '18 at 01:19
  • 1
    okay I tried on my sytem it worked as expected but when I manupilated the path of my source file in following code ScriptRunner.RunFromCmd(@"C:\Users\xyzz\Desktop\test.py", args); I got exit code 2. – Apoorva Raju Sep 20 '18 at 07:29
  • Had an extra space in my path. Now it worked. Thanks Apoorva – swifty Sep 23 '18 at 04:42