Fix Python – Capture stdout from a script?


Asked By – Paolo

suppose there is a script doing something like this:

# module
import sys

def write():

Now suppose I want to capture the output of the write function and store it in a variable for further processing. The naive solution was:

# module
from writer import write

out = write()
print out.upper()

But this doesn’t work. I come up with another solution and it works, but please, let me know if there is a better way to solve the problem. Thanks

import sys
from cStringIO import StringIO

# setup the environment
backup = sys.stdout

# ####
sys.stdout = StringIO()     # capture output
out = sys.stdout.getvalue() # release output
# ####

sys.stdout.close()  # close the stream 
sys.stdout = backup # restore original stdout

print out.upper()   # post processing

Now we will see solution for issue: Capture stdout from a script?


Setting stdout is a reasonable way to do it. Another is to run it as another process:

import subprocess

proc = subprocess.Popen(["python", "-c", "import writer; writer.write()"], stdout=subprocess.PIPE)
out = proc.communicate()[0]
print out.upper()

This question is answered By – Matthew Flaschen

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0