python - 子流程内的子流程。如何传播错误输出?

标签 python subprocess

我使用子进程来运行脚本。但是那个被调用的脚本本身使用子进程来执行一些命令。问题是,当我在外部脚本中捕获异常时,它只是说调用的脚本中存在错误。

所以,我的问题是如何将错误从内部脚本传播到外部脚本,以便我知道内部脚本中发生的确切原因。

这就是我如何使用子进程捕获异常并在错误时退出。

try:
    output = subprocess.check_output(cmd)
except Exception as e:
    print(str(e))
    sys.exit(1)

最佳答案

如果您使用subprocess python模块,您可以分别处理命令的STDOUT、STDERR和返回码。您可以查看完整命令调用程序实现的示例。当然,如果您愿意,您可以使用 try.. except 扩展它。

下面的函数返回 STDOUT、STDERR 和返回代码,以便您可以在其他脚本中处理它们。

import subprocess

def command_caller(command=None)
    sp = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=False)
    out, err = sp.communicate()
    if sp.returncode:
        print(
            "Return code: %(ret_code)s Error message: %(err_msg)s"
            % {"ret_code": sp.returncode, "err_msg": err}
            )
        # You can raise an error if the return code of command is not zero.
        # raise Exception(
        #   "Return code: %(ret_code)s Error message: %(err_msg)s"
        #   % {"ret_code": sp.returncode, "err_msg": err}
        #   )
    return sp.returncode, out, err

关于python - 子流程内的子流程。如何传播错误输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56219578/

相关文章:

python - 从 bottle.template 切换到 mako

python - Matplotlib Table Bbox - 如何控制位置和样式?

python - 是否有任何好的选项可以将 Django 站点烘焙为静态文件?

python - 通过 PYODBC 的 SQL 查询在一台机器上默默失败,在另一台机器上工作

python - 从 Python 中的 imagemagick 子进程读取输出

python - 让 subprocess.Popen 只等待其子进程返回,而不等待任何孙子进程返回

python - 初学者 Django : next button acts as Submit

python - 如何获取包含管道的 Python 子进程命令的输出?

python - 子进程,stderr 到 DEVNULL 但打印错误

python - 从子进程中实时捕获标准输出