Python调用makefile编译并捕获make的输出

liu*_*uzw 5 python subprocess makefile

Jenkins 中的一项工作调用我的 python 脚本,我想在其中调用make以编译我的 UT 代码,并sys.exit(1)在出现诸如“make: *** [ ] Error 1”之类的编译错误时引发。

我还需要实时打印输出。

这是我的python脚本:

make_process = subprocess.Popen("make clean all;", shell=True, stdout=subprocess.PIPE, stderr=sys.stdout.fileno())
    while True:
        line = make_process.stdout.readline()
        if not line:break
        print line, #output to console in time
        sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)

但是如何捕获make错误并让这个 python 脚本失败?

笔记:

更新: 原来是一个makefile问题。请参阅对已接受答案的评论。但是对于这个python问题,pentadedecagon给出了正确的答案。

pen*_*gon 5

您可以通过以下方式检查make过程的返回值

make_process.poll()
Run Code Online (Sandbox Code Playgroud)

如果进程仍在运行,则返回“None”;如果进程已完成,则返回错误代码。如果您只是希望输出最终出现在控制台上,则无需手动执行此操作。输出无论如何都会到达控制台,并且可以这样做:

make_process = subprocess.Popen("make clean all", stderr=subprocess.STDOUT)
if make_process.wait() != 0:
     something_went_wrong();
Run Code Online (Sandbox Code Playgroud)