Redirect an output command to a variable or file?
Question: I'm trying to write a python script that will allow me to take the output from
a command and to put that into a file or variable (Preferability a variable).

In my code, I have redirected the output to a `StringIO()` object. From that,
I want take the output a command and to put it into that `StringIO()` object.

Here is a sample of my code:

    
    
    from StringIO import StringIO
    import sys
    
    old_stdout = sys.stdout
    
    result = StringIO()
    sys.stdout = result
    
    # This will output to the screen, and not to the variable
    # I want this to output to the 'result' variable
    os.system('ls -l')
    

Also, how do I take result and put it into a string?

Thanks in advance!!


Answer: 
    import subprocess
    sp = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
    output, _ = sp.communicate()
    print "Status:", sp.wait()
    print "Output:"
    print output
    

