0

Thanks to this post, I managed to call python script from C#, however, I am not able to detect if the python code threw an exception. For example given a python script

def test():
    raise Exception

my C# code

Process p = new Process();
p.StartInfo = new ProcessStartInfo(cmd, args)
{
    RedirectStandardOutput = true,
    UseShellExecute = false,
    CreateNoWindow = true
};
p.Start();

using (StreamReader reader = p.StandardOutput)
{
    string stderr = p.StandardError.ReadToEnd();
    string result = reader.ReadToEnd(); 
}

can not read the error message by string stderr = p.StandardError.ReadToEnd(); In fact itself threw an exception "An unhandled exception of type 'System.InvalidOperationException' occurred in System.dll"

How can I solve this?

1
  • What details are contained in InvalidOperationException? Commented Jul 14, 2017 at 4:27

1 Answer 1

1

In order to use string stderr = p.StandardError.ReadToEnd(); you have to redirect the error output add RedirectStandardError = true to your process initialization like so:

Process p = new Process();
p.StartInfo = new ProcessStartInfo(cmd, args)
{
    RedirectStandardOutput = true,
    UseShellExecute = false,
    CreateNoWindow = true,
    RedirectStandardError = true
};
p.Start(); 
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.