Returning Values from Bash Scripts

Steven D'Aprano steve at
Sat Jan 7 23:00:04 EST 2006

On Sat, 07 Jan 2006 22:03:36 -0500, Mike Meyer wrote:

> chakkaradeepcc at writes:
>> How to execute bash scripts from python (other than using os.popen) and
>> get the values that those bash scripts return.
> The easy way is to call it with

>>> import subprocess
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ImportError: No module named subprocess

It might be easy, but an awful lot of people won't be using a version of
Python that has the subprocess module, and for them upgrading may not be
easy (or even possible) at all.

For those that don't have access to subprocess, there is an embarrassment
of riches available. You can do this:

>>> result = os.system('ls')  file.txt
>>> result

If you want to capture the result of the command, you can try this:

>>> output = os.popen('ls -l').read()

Perhaps the simplest way if subprocess is not available to you is the
commands module. Other possibilities are os.fork, os.execv and the popen2
module. There may be other solutions as well.


More information about the Python-list mailing list