pythonc#return-valueprocessstartinfo

How to return the "return value" of a python script in C#?


I want to run a python script in C# and then want to return the "return value" of the python script into C#.

My python script:

def myfunc():
    print("aaa")
    return "abc"

if __name__ == "__main__":
     myfunc()

My C# file:

void Main()
{
    var result = run_cmd();
    Console.WriteLine(result);
}


private string run_cmd()
{

    string fileName = @"C:\Users\NCH-Lap10\Desktop\return_one.py";
    string python = @"C:\Users\NCH-Lap10\AppData\Local\Programs\Python\Python37-32\python.exe";

    Process psi = new Process();
    psi.StartInfo = new ProcessStartInfo(python, fileName)
    {
        RedirectStandardOutput = true,
        UseShellExecute = false,
        CreateNoWindow = false
    };
    psi.Start();

    string output = psi.StandardOutput.ReadToEnd();
    Console.WriteLine(output);
    
    psi.WaitForExit();
    int result = psi.ExitCode;
        
    return output;
}

I can return the printed message "aaa" but I need "abc". I assumed the psi.ExitCode would give me the needed output but it is not working.


Solution

  • Your script returns the value of myfunc only internally. If you want to export the value, you can write print(myfunc()) after the main-if. Also check this answer as it discusses various methods and concepts