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?

Community
  • 1
  • 1
user846121
  • 21
  • 1
  • 2

3 Answers3

9
import subprocess
command = raw_input("Enter command: ")
p = subprocess.Popen(command, stdout=subprocess.PIPE)
output, error = p.communicate()
agf
  • 171,228
  • 44
  • 289
  • 238
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.

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
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'
ironchefpython
  • 3,409
  • 1
  • 19
  • 32
  • All of the old popen interfaces are deprecated in favor of subprocess. – Chris Eberle Jul 18 '11 at 17:21
  • @Chris I was wondering what "DeprecationWarning: The popen2 module is deprecated. Use the subprocess module." meant... – ironchefpython Jul 18 '11 at 17:25
  • Sarcasm. Yes I've heard tell of such things. – Chris Eberle Jul 18 '11 at 17:26
  • 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. – ironchefpython Jul 18 '11 at 20:34
  • 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`. – Chris Eberle Jul 18 '11 at 20:45
  • http://mail.python.org/pipermail/python-3000/2008-March/012421.html for reference. That doesn't mean that individual distros aren't free to do the wrong thing. IIRC Gentoo is also looking to make the 2 -> 3 symlink switch. But... if you've successfully built and administered your own arch or gentoo box, you're probably not using stackoverflow as a google proxy. – ironchefpython Jul 18 '11 at 21:00
  • @Chris let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/1596/discussion-between-ironchefpython-and-chris) – ironchefpython Jul 18 '11 at 21:01