2

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!!

1

1 Answer 1

5
import subprocess sp = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE) output, _ = sp.communicate() print "Status:", sp.wait() print "Output:" print output 
Sign up to request clarification or add additional context in comments.

2 Comments

In my real code, I'm not using ls -l. I'm using the command find *. When I use find * in place of ls -l from the code you have in your comment, it doesn't give anything, though when I go to the normal command line, it outputs everything normal. When I use ls -l it works fine. Suggests?
You can use the Popen() argument shell=True and give it a string to be executed. Or you could use ['find', '.'] which should essentially be the same, more or less.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.