0

I want to execute shell commands(Let say ubuntu's ls -a command)

Now, after reading few SOF threads, I've found that the subprocess module is best. Is that really the case?

from subprocess import call
t = call(['ls', '-a'])
print t

When I run this script it simply printed the result on my system's terminal, and the variable t got the value 0.

shell=False is also not working; I just gave it a try.

How could I store result in a variable instead of printing it to the terminal (or may be to the terminal as well, if it is not possible to get rid of this)?

Can we use any other library for this purpose?

EDIT:

t = os.popen('ls -a').read()

This is working! But is there any bug, or some issue with this?

Nancy
  • 997
  • 1
  • 8
  • 12
  • There are plenty of third-party libraries on PyPI that are higher-level than `subprocess` that you might want to take a look at. For what you're doing, you probably don't need any of their fancy stuff, but you may find them useful in the future. – abarnert Aug 10 '14 at 19:27
  • 1
    By the way, that `0` is the return value of the `ls` program. Every program returns a small integer as a value, with 0 almost always meaning success. Just like the shell has different ways to run a program and store its return value, vs. running a program and capturing its output, `subprocess` has different functions for the two. – abarnert Aug 10 '14 at 19:29

2 Answers2

2

Use subprocess.check_output to capture the output.

from subprocess import check_output
t = check_output(['ls', '-a'])
print t

Note that this will raise a CalledProcessError exception if ls were to return a non-zero exit-code.

As for the other part of your question, the subprocess module is the preferred (and best, IMO) way to run sub-processes in Python. You should favor it over os.popen.

dano
  • 91,354
  • 19
  • 222
  • 219
  • How do I pass the password if I'm using `sudo`. if I simply write `t = check_output(['sudo', 'ls', '-a'])` then it asks me to enter password but is there any way to pass in my program. – Nancy Aug 11 '14 at 17:04
0
from subprocess import PIPE,Popen
t = Popen(['ls', '-a'],stdout=PIPE)
t = t.communicate()[0]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • While this might answer the question, please add a bit of comment to it what your are doing and why! – Blitz Aug 10 '14 at 21:05