1

I'm using the subprocess module to execute my C program, and at the end I want to get both the return code and the output returned from the program. I tried this:

result = subprocess.check_output(['src/main', '-n {0}'.format(n)], universal_newlines=True) 

The above captures the output of the program, it will only raise an error if the return code is non-zero. The point is that I do not want to raise an error on non-zero error code, instead I want to use it in an if statement, and if the return code is non-zero I want to re-run the process.

Now, if I change it to run, and call as:

result = subprocess.run(['src/main', '-n {0}'.format(n)]) 

Then, I can do result.returncode to get the return code, but when I do result.stdout, it prints None. Is there a way to get both the return code and the actual output?

1 Answer 1

1

In order to capture output with subprocess.run(), you need to pass stdout=subprocess.PIPE. If you want to capture stderr as well, also pass stderr=subprocess.PIPE (or stderr=subprocess.STDOUT to cause stderr to be merged with stdout in the result.stdout attribute). For example:

result = subprocess.run(['src/main', '-n {0}'.format(n)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 

Or, if you are using Python 3.7 or higher:

result = subprocess.run(['src/main', '-n {0}'.format(n)], capture_output=True) 

You may also want to set universal_newlines=True to get stdout as a string instead of bytes.

Sign up to request clarification or add additional context in comments.

Comments