本文介绍了捕获python子进程异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python脚本,在其中使用如下所示的子进程调用另一个脚本.

I have a python script where i am calling another script using subprocess as below.

        sp = subprocess.Popen("script.py --arg1 --arg2', cwd=GIVEN_PATH, shell=True, stdout=subprocess.PIPE,  stderr=subprocess.STDOUT)

        while sp.poll() is None:
            for out in iter(sp.stdout.readline,''):
                self.log(out.rstrip())

这对我来说很好,但是我想从script.py中获取任何异常.我知道我们可以获取重新编码,但实际上我需要获取完整的异常信息.

This is working fine for me but i want to get any exception from the script.py. I know we can get the retcode but i actually need to get the full exception information.

如果script.py加薪

If script.py raises

         raise IOERROR("got an exception")

那我需要知道这些信息.simailar方法是获取sys.exc_info()等.

then i need to know this information. simailar way we get the sys.exc_info() etc.

有没有办法做到这一点?

is there a way i can do this?

预先感谢

推荐答案

不,您无法从子进程中获取 sys.exc_info() -在您能够看到返回码,子进程在内存中的对象(包括堆栈跟踪)已经消失了.

No, you can't get the sys.exc_info() from a subprocess -- by the time you're able to see the return code, objects in memory (including stack traces) of the child process are already gone.

您可以做的是,通过为stderr输出提供一个单独的管道并读取它,来解析子进程写入stderr的文本.假设您的程序从未以其他方式写入stderr,则在该流中显示的唯一文本将是错误消息和堆栈跟踪.

What you can do is parse the text your subprocess writes to stderr, by providing a separate pipe for the stderr output and reading that. Assuming that your program never writes to stderr otherwise, the only text that will show up in that stream will be the error message and stack trace.

但是,您将需要谨慎使用此方法,因为如果该进程向stderr中写入的文本多于您可以缓冲的文本,则将导致死锁.最好的解决方案是让一个单独的线程从stdout和stderr中并行读取.

You'll want to be cautious with this approach, though, because if the process writes more text to stderr than you can buffer, you'll deadlock. The best solution is to have a separate thread to read from both stdout and stderr in parallel.

这篇关于捕获python子进程异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 05:25