在c中从python脚本捕获运行时异常和输出#

2024-04-25 20:44:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个运行python脚本的WCF服务。在

为此,我使用了以下代码:

ProcessStartInfo start = new ProccessStartInfo();
start.FileName = "my/full/path/to/python.exe";
start.Arguments = string.Format("{0} {1}", script, args);
start.UseShellExecute = false;
start.CreateNoWindow = true;
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;

Process p = new Process();
p.StartInfo = start;
p.Start();
p.WaitForExit();
string stderr = Process.StandardError.ReadToEnd();
string stdout = Process.StandardOutput.ReadToEnd();

现在我注意到(经过大量测试)Process对象获得标准错误/输出,或者在错误与“编译”错误相关时捕获异常,比如我使用了未声明的变量或类似的东西,但是运行时异常和打印在C范围内没有被捕获或无法读取。在

我已经试过了python.exepythonCommand.pyargs“是从C代码发送的,或者只是发送ProcessStartInfo.参数在命令行提示符中,它返回异常并在两种情况下打印,但是,当我通过C#Process对象运行它时,我没有遇到任何异常,也没有任何输出或错误。在

我没有发现任何让我觉得有点蠢的事情(希望我是,这有一个简单的解决办法),如果有人偶然发现这个案子,我会非常感激的。在

谢谢, 马特


Tags: 对象代码脚本truenewstringmy错误
1条回答
网友
1楼 · 发布于 2024-04-25 20:44:18

好吧,在这里回答你的意见:

But the problem is both the Exception not being thrown from the the python nor an output to be read. The Standard Output of the process (and the Standard Error as well) are always empty – Matt Star

您捕获的输出错误。这将允许您捕获输出,并应显示引发的任何异常。在

使用系统; 使用系统诊断

namespace InteractWithConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
            cmdStartInfo.FileName = @"C:\Windows\System32\cmd.exe";
            cmdStartInfo.RedirectStandardOutput = true;
            cmdStartInfo.RedirectStandardError = true;
            cmdStartInfo.RedirectStandardInput = true;
            cmdStartInfo.UseShellExecute = false;
            cmdStartInfo.CreateNoWindow = true;

            Process cmdProcess = new Process();
            cmdProcess.StartInfo = cmdStartInfo;
            cmdProcess.ErrorDataReceived += cmd_Error;
            cmdProcess.OutputDataReceived += cmd_DataReceived;
            cmdProcess.EnableRaisingEvents = true;
            cmdProcess.Start();
            cmdProcess.BeginOutputReadLine();
            cmdProcess.BeginErrorReadLine();

            cmdProcess.StandardInput.WriteLine("ping www.bing.com");     //Execute ping bing.com
            cmdProcess.StandardInput.WriteLine("exit");                  //Execute exit.

            cmdProcess.WaitForExit();
        }

        static void cmd_DataReceived(object sender, DataReceivedEventArgs e)
        {
            Console.WriteLine("Output from other process");
            Console.WriteLine(e.Data);
        }

        static void cmd_Error(object sender, DataReceivedEventArgs e)
        {
            Console.WriteLine("Error from other process");
            Console.WriteLine(e.Data);
        }
    }
}

我从这篇文章中复制了代码:How to parse command line output from c#? 我用过很多次这种方法,效果很好。 这有助于希望。在

相关问题 更多 >