2

Possible Duplicate:
Running shell command from python and capturing the output

I want to capture the output of a command into a variable, so later that variable can be used again. I need to change this script so it does that:

#!/usr/bin/python
import os
command = raw_input("Enter command: ")
os.system(command)

If I enter "ls" when I run this script, I get this output:

Documents Downloads Music Pictures Public Templates Videos

I want to capture that string (the output of the ls command) into a variable so I can use it again later. How do I do this?

0

3 Answers 3

9
import subprocess
command = raw_input("Enter command: ")
p = subprocess.Popen(command, stdout=subprocess.PIPE)
output, error = p.communicate()
Sign up to request clarification or add additional context in comments.

Comments

2

The output of the command can be captured with the subprocess module, specifically, the check_output function..

output = subprocess.check_output("ls")

See also the documentation for subprocess.Popen for the argument list that check_output takes.

Comments

0

This is the way I've done it in the past.

>>> import popen2
__main__:1: DeprecationWarning: The popen2 module is deprecated.  Use the subprocess module.
>>> exec_cmd = popen2.popen4("echo shell test")
>>> output = exec_cmd[0].read()
>>> output
'shell test\n'

7 Comments

All of the old popen interfaces are deprecated in favor of subprocess.
@Chris I was wondering what "DeprecationWarning: The popen2 module is deprecated. Use the subprocess module." meant...
Sarcasm. Yes I've heard tell of such things.
On a serious note, his sha-bang is #!/usr/bin/python, which means he's using a 2.x rather than a 3.x, and subprocess.check_output didn't come along until 2.7, so I figured giving him the old way of doing it had the most likely chance of success. I left the deprecation warning in the console output so it would be clear there's a newer way to do it, if he has the latest version of Python.
A shebang of /usr/bin/python means whatever it means. I run arch linux and /usr/bin/python is version 3. Version 2 is located at /usr/bin/python2.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.