4

Possible Duplicate:
How can I capture the stdout output of a child process?

I'm running a cat-like program in bash from Python:

   import os

   os.system('cat foo.txt')

How do I get the output of the shell command back in the Python script, something like:

   s = somefunction('cat foo.txt')

?

UPD: Here is a related thread.

Community
  • 1
  • 1
Alex
  • 43,191
  • 44
  • 96
  • 127

1 Answers1

16

Use the subprocess module.

from subprocess import Popen, PIPE

(stdout, stderr) = Popen(["cat","foo.txt"], stdout=PIPE).communicate()
print stdout
ismail
  • 46,010
  • 9
  • 86
  • 95