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

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

7 Comments

i get proc.ExitCode=2 and not 0
Does the python code work outside C# code ? I meant in command prompt ? Issue might be with python script
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)
Strange , did you change the path of Python.exe ?? i had python37 on my system .
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.