【问题标题】:Why does subprocess.run return an exit code of 2 but no errors in log?为什么 subprocess.run 返回退出代码 2 但日志中没有错误?
【发布时间】:2021-05-27 21:57:27
【问题描述】:

我目前正在使用下面指定的参数运行子进程。 一切似乎运行良好。生成的输出符合预期,生成的日志没有显示错误。

exit_code = subprocess.run([cmd, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11], capture_output=True)

但是我得到的返回码/退出码为 2。

当我打印上面的 exit_code 时,stderr & stdout 显示以下内容。

returncode=2, stderr=b'', stdout=b''

为什么我会得到预期的输出并且日志中没有错误但仍然得到退出代码 2? 有没有办法找出退出代码返回 2 的原因? b'' 对 stderr 和 stdout 意味着什么?

我正在使用 subprocess.run 运行 SAS 程序。 这只发生在某些 SAS 程序中。 它确实发生的一个似乎生成pdf文件。 此外,如果我将 subprocess.run 中指定的完全相同的参数用于 .bat 文件,它运行良好,退出代码为 0。

【问题讨论】:

  • 这取决于cmd。你可以显示正在运行的命令吗?

标签: python error-handling sas subprocess


【解决方案1】:

首先,很高兴知道您使用的是什么操作系统。 stderrstdout 基本上是文件描述符(默认为 1 和 2。)

在您的情况下,子命令不会向 1 和 2 文件描述符写入任何内容(因此写入 stderrstdout),当然返回码是 2

如果你运行以下代码:

import subprocess

result = subprocess.run(["echo", "test"])
print(result.returncode, result.stdout, result.stderr)

你得到:

>>> python3 test.py
test
0 None None

这意味着echo 正确运行并将test 写入STDOUT,但result.stdout 不包含它。发生这种情况,但您没有将命令的 STDOUT 重定向到 PIPE。

如果您将代码更改为:

import subprocess

result = subprocess.run(["echo", "test"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(result.returncode, result.stdout, result.stderr)

你会得到:

>>> python3 test.py
0 b'test\n' b''

所以现在result.stdout 包含被调用命令的 STDOT(以字节为单位)。 STDERR 是这样。

如果将shell 参数设置为True,我可以运行无效(不存在)命令,如下所示:

import subprocess

result = subprocess.run(["invalid_cmd"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
print(result.returncode, result.stdout, result.stderr)

在这种情况下,输出是:

>>> python3 test.py
127 b'' b'/bin/sh: invalid_cmd: command not found\n'

表示返回码为 127,STDOUT 为空,但 STDERR 包含/bin/sh: invalid_cmd: command not found\n 消息(以字节为单位)。

如果您执行了上述操作但没有看到任何输出,那么您的调用命令不会写入 STDOUT 或 STDERR,因此您应该查看调用的命令。

【讨论】:

  • 操作系统是 Windows 10。问题似乎与 SAS 程序本身有关,而不是 subprocess.run() 命令。您提供的信息对于理解问题出在 SAS 程序而不是 subprocess.run() 命令非常有帮助。
  • 不客气!我希望你能解决 SAS cmd。 :)
猜你喜欢
  • 1970-01-01
  • 2011-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-01
  • 2021-04-01
相关资源
最近更新 更多