【发布时间】:2017-04-04 17:37:14
【问题描述】:
我有一个从 C# 调用的 python 脚本。下面提供的代码。此过程的问题是,如果 Python 脚本失败,我将无法在 C# 中理解并显示该异常。我正在使用 C#、MVC、Python。您能否修改以下代码并告诉我如何捕获 Python 脚本异常时抛出的异常?
Process process = new Process();
Stopwatch stopWatch = new Stopwatch();
ProcessStartInfo processStartInfo = new ProcessStartInfo(python);
processStartInfo.UseShellExecute = false;
processStartInfo.RedirectStandardOutput = true;
try
{
process.StartInfo = processStartInfo;
stopWatch.Start();
//Start the process
process.Start();
// Read the standard output of the app we called.
// in order to avoid deadlock we will read output first
// and then wait for process terminate:
StreamReader myStreamReader = process.StandardOutput;
string myString = myStreamReader.ReadLine();
// wait exit signal from the app we called and then close it.
process.WaitForExit();
process.Close();
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Session["Message"] = "Success";
}
catch (InvalidOperationException ex)
{
throw new System.InvalidOperationException("Bulk Upload Failed. Please contact administrator for further details." + ex.StackTrace);
Session["Message"] = "Failed";
}
【问题讨论】:
-
添加这一行
processStartInfo.RedirectStandardError = true;并更改 tis line :StreamReader myStreamReader = process.StandardOutput + process.StandardError;以读取错误。 -
StreamReader myStreamReader = process.StandardOutput + process.StandardError;就像抛出编译错误一样。谢谢。
-
嘿亚当 - 你的答案非常接近。我修改了代码并从 StandardError 获得了整个异常堆栈。我提供了以下代码的工作版本作为答案。感谢您的提示。 - 谢谢。
标签: c# python exception process exception-handling