简体   繁体   中英

How to get both the output and return code with subprocess?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM