0

Below is a small code segment in the python script I wrote. The purpose of the script is to compile various C files. (I modified the segment and simplified it to fit the purpose of the question.)

    fileName = "somefile.c"
    my_cmd = "gcc -std=c99 -Wall " + fileName[-2:0] + " .o " + fileName
    os.system(my_cmd)

This works well. But I want to keep track of which file got compiled without warnings and which file showed warnings.

To check if the file compiled successfully is not a problem. I can either check the return value of os.system() or I can check if the corresponding object file got created or not.

But how can I check if the somefile.c had any warnings during compilation? Thanks!

What I have tried:

I tried using the ">" operator (redirection) but that is not working. I used something like:

os.system(my_cmd + " > output")

No matter what the contents of somefile.c are, the file named output is always created and is empty!!

Avi Dubey
  • 794
  • 6
  • 16

1 Answers1

1

Processes in general get two output streams. One is stdout, has file number 1 and is (unsurprisingly) for standard output. The other is for errors and warnings and is generally called stderr and has file number 2. To redirect the stderr in the shell you would do:

gcc file.c -o file 2> some_file

This will give you a file called "some_file" containing whatever gcc wrote to the stderr (including the information you want). Using this as a string with os.system would work but is highly not recommended. You should (almost certainly) use the subprocess module instead. Here is an example:

import subprocess as s

p = s.Popen(["gcc", "-std=c99", "-Wall", "test.c", "-o", "test"], stdout=s.PIPE, stderr=s.PIPE)

p_stdout, p_stderr = p.communicate()

print "*****STDOUT*****"
print p_stdout
print "*****STDERR*****"
print p_stderr
or1426
  • 929
  • 4
  • 7