通过 C# 控制台执行时如何处理 NPM/Newman failure/hanging

How to handle NPM/Newman failure/hanging when executed via C# console

我有在 C# 中创建的方法(如下所示),它通过 C# 控制台应用程序执行一些 npm/newman 命令。当前代码处理 cmd hangs/failed,但不处理 nmp/newman 执行挂起或失败的情况。

你能帮忙解决一下吗?

public string Runner ()
    {
        var psiNpm = new ProcessStartInfo
        {
            FileName = "cmd",
            RedirectStandardOutput = true,
            RedirectStandardInput = true,
            UseShellExecute = false
        };
        var pNpmRun = Process.Start(psiNpm);
        pNpmRun.StandardInput.WriteLine("npm install -g newman");
        pNpmRun.StandardInput.WriteLine("newman run " +
            "\"C:\Postman\Test.postman.json\" " +
            "--folder \"TestSearch\" " +
            "--environment \"C:\Postman\postman_environment.json\" " +
            "--disable-unicode");
        pNpmRun.StandardInput.WriteLine("exit");

          var tenMin = 10 * 60 * 1000;
          if(pNpmRun.WaitForExit(tenMin)) {
             return pNpmRun.StandardOutput.ReadToEnd();
          } else {
             pNpmRun.Kill();
             throw new TimeoutException("Command didn't complete in 10 minute timeout");
          }
    }

您可以检查 npmnewman 命令的退出代码,并 return 它们到调用进程:

public string Runner ()
    {
        var psiNpm = new ProcessStartInfo
        {
            FileName = "cmd",
            RedirectStandardOutput = true,
            RedirectStandardInput = true,
            UseShellExecute = false
        };
        var pNpmRun = Process.Start(psiNpm);
        pNpmRun.StandardInput.WriteLine("npm install -g newman");

        pNpmRun.StandardInput.WriteLine("if not "%ERRORLEVEL%" == "0" exit 1");

        pNpmRun.StandardInput.WriteLine("newman run " +
            "\"C:\Postman\Test.postman.json\" " +
            "--folder \"TestSearch\" " +
            "--environment \"C:\Postman\postman_environment.json\" " +
            "--disable-unicode");

        pNpmRun.StandardInput.WriteLine("if not "%ERRORLEVEL%" == "0" exit 2");
        pNpmRun.StandardInput.WriteLine("exit 0");

          var tenMin = 10 * 60 * 1000;
          if(pNpmRun.WaitForExit(tenMin)) {
             var exitCode = pNpmRun.ExitCode;
             if(exitCode != 0) {
               throw new Exception("Command failed " + exitCode);
             }
             return pNpmRun.StandardOutput.ReadToEnd();
          } else {
             pNpmRun.Kill();
             throw new TimeoutException("Command didn't complete in 10 minute timeout");
          }
    }

在每个命令之后检查 errorlevel,这是一个 "virtual environment variable",代表前一个命令的退出代码。如果它不是 0(通常是成功),那么它将退出 cmd 进程并返回到您的 C# 代码。您的 C# 代码检查进程的 ExitCode,如果不成功 (0),它会抛出包含 ExitCode 的异常,以便您知道这两个命令中的哪一个失败了。这依赖于 npmnewman 进程 return 在失败时使用非零退出代码。

那应该可以处理 "failure"。处理 "hanging" 会更困难。真的没有任何方法可以知道这个过程是否会return(阅读:停止问题(我在大学学到的一件事))。