capture compiling error using python subprocess

Viewed 29

Using Python to script running GoogleTest with subprocess.

My code looks like

import subprocess
import logging

logging.basicConfig(filename="gtest.log",level=logging.INFO, format='%(asctime)s:%(levelname)s:%(message)s')

output = subprocess.check_output("g++ test.cpp -lgtest -lgtest_main -lpthread -I <some header file path>",shell = True)

logging.info(output.decode("utf-8"))

The log file only contains the executable output after compiling is a success. Sometimes, there are missing header files and the compiler will throw an error, for example:

fatal error: profile.h: No such file or directory

However, this will not be captured in the log.

My understanding is, since the compilation failed, there is never an output variable created. subprocess just executed the command and goes to the next when the previous is finished. Python cannot catch that error generated via g++.

Am I thinking it correctly? and if I want to capture the g++ compiling error into the log, what should I do?

1 Answers

Refer to the comment via @Miles Budnek:

g++ prints errors to stderr, so you need to capture that as well as stdout. Add stderr=subprocess.STDOUT to your call to capture it as well.

Related