28

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.

3
  • you need popen PIPE, system probably returns process termination status Commented Oct 8, 2013 at 8:45
  • @GrijeshChauhan I tried it as well but couldn't make it work. Can you show an example? Commented Oct 8, 2013 at 8:46
  • @S4M Read: docs.python.org/2/library/subprocess.html#popen-constructor Commented Oct 8, 2013 at 8:48

1 Answer 1

78

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()
Sign up to request clarification or add additional context in comments.

4 Comments

An example using subprocess will be helpful :)
Added an example with subprocess
tmp = os.popen("ls").read() is fine. I have python 2.6.
why subprocess may be better?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.