In Python, get the output of system command as a string

Question:

In python I can run some system command using os or subprocess. The problem is that I can’t get the output as a string. For example:

>>> tmp = os.system("ls")
file1 file2
>>> tmp
0

I have an older version of subprocess that doesn’t have the function check_out, and I would prefer a solution that doesn’t require to update that module since my code will run on a server I don’t have full admin rights.

Asked By: S4M

||

Answers:

Use os.popen():

tmp = os.popen("ls").read()

The newer way (> python 2.6) to do this is to use subprocess:

proc = subprocess.Popen('ls', stdout=subprocess.PIPE)
tmp = proc.stdout.read()
Answered By: Hari Menon
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.