3

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.

1
  • I think, you need a embeded Python interpreter for this. If your data is simple and serializable, consider passing the data with a socket. Commented Jul 31, 2020 at 8:33

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

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.