c# - 如何确定从 C# 运行的 python 脚本已通过或失败

标签 c# process

我有以下从 C# 调用 Python 应用程序的代码,有没有办法确定从 C# 运行的 python 脚本是通过还是失败?我们是否得到任何退出/返回代码,表明从 C# 运行的 python 应用程序是成功还是失败

using System;
using System.IO;
using System.Diagnostics;

namespace CallPython
{
        class Program
    {
        static void Main(string[] args)
        {
            string python = @"C:\\Python27\python.exe";
            string myPythonApp = @"C:\\Dropbox\scripts\loadbuild\sum.py";
            int x = 2;
            int y = 5;

            ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);

            myProcessStartInfo.UseShellExecute = false;
            myProcessStartInfo.RedirectStandardOutput = true;
            myProcessStartInfo.Arguments = myPythonApp + " " + x + " " + y;
            Process myProcess = new Process();
            myProcess.StartInfo = myProcessStartInfo;
            myProcess.Start();
            StreamReader myStreamReader = myProcess.StandardOutput;
            string myString = myStreamReader.ReadToEnd();
            myProcess.WaitForExit();
            myProcess.Close();
            Console.WriteLine("Value received from script: " + myString);
            Console.ReadLine();

        }
    }
}

最佳答案

除了程序写入其(标准)输出 channel 的输出外,程序总是以exit status终止。 (或退出代码)。如果程序正确运行,则程序应以 0 退出,如果出现错误,则应以 0 以外的退出代码退出。

现在,当发生算术错误时,python 程序通常会以 0 以外的退出状态退出,例如程序:

a = 4/0

不仅会产生错误信息:

Traceback (most recent call last):
  File "test.ply", line 1, in <module>
    a = 4/0
ZeroDivisionError: integer division or modulo by zero

但也返回退出状态 1。现在显然 python 程序员可以使用 try-catch 处理,这样错误就不会导致非零的退出状态,但这会 - 至少部分地 - 击败使用退出状态。

如果 python 程序的程序员在错误正确时执行退出代码,或者错误是算术错误,则 python 程序将退出并退出非零代码。

您可以使用 Process.ExitCode 捕获退出代码.

在文档手册中,我们可以看到:

Developers usually indicate a successful exit by an ExitCode value of zero, and designate errors by nonzero values that the calling method can use to identify the cause of an abnormal process termination. It is not necessary to follow these guidelines, but they are the convention.

例如:

//...
myProcess.WaitForExit();
int ec = myProcess.ExitCode;
if(ec != 0) {
    //oops the Python program made an error
} else {
    //assume everything went fine
}

关于c# - 如何确定从 C# 运行的 python 脚本已通过或失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38234519/

相关文章:

c# - 如何使用进度条连接多个文本框?

c# - 将 zip 文件编码为 Base64

c# - 如何在c#中执行命令?

c - 如何将C中的进程拆分为不同的进程?

c - 在 C 中的两个索引挂起进程之间共享数据

java - Linux 从 Java 控制台应用程序中杀死 Java 进程

c# - Entity Framework 中多对多关系中的多个实体

c# - 为什么我的机器需要完全重置 IIS 才能看到 ASP.NET 项目的代码更改?

c# - Azure Functions 无法从 ABCpdf Nuget 包加载 DLL

macos - 在 OSX/Unix 上启动一个不继承文件/端口的子进程