Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting console output to a Python string [duplicate]

Tags:

python

bash

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.

like image 682
Alex Avatar asked Dec 03 '22 15:12

Alex


1 Answers

Use the subprocess module.

from subprocess import Popen, PIPE

(stdout, stderr) = Popen(["cat","foo.txt"], stdout=PIPE).communicate()
print stdout
like image 87
ismail Avatar answered Dec 27 '22 06:12

ismail