19

In Python I need to get the version of an external binary I need to call in my script.

Let's say that I want to use Wget in Python and I want to know its version.

I will call

os.system( "wget --version | grep Wget" ) 

and then I will parse the outputted string.

How to redirect the stdout of the os.command in a string in Python?

1

4 Answers 4

41

One "old" way is:

fin,fout=os.popen4("wget --version | grep Wget")
print fout.read()

The other modern way is to use a subprocess module:

import subprocess
cmd = subprocess.Popen('wget --version', shell=True, stdout=subprocess.PIPE)
for line in cmd.stdout:
    if "Wget" in line:
        print line
Sign up to request clarification or add additional context in comments.

1 Comment

subprocess is new since python 2.4.
10

Use the subprocess module:

from subprocess import Popen, PIPE
p1 = Popen(["wget", "--version"], stdout=PIPE)
p2 = Popen(["grep", "Wget"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

Comments

-2

Use subprocess instead.

3 Comments

does Subprocess.popen calls shell to parse command and runs an extra process in Python.
@Grijesh: Only if you tell it to.
In 'C' I only use low level pipe() but in Python I saw people use subproces.popen() even there is os.pipe(). which practice is good? Although I can see subprocess.popen() is more powerful then C popen() we can explicitly send parsed command in python.
-3

If you are on *nix, I would recommend you to use commands module.

import commands

status, res = commands.getstatusoutput("wget --version | grep Wget")

print status # Should be zero in case of of success, otherwise would have an error code
print res # Contains stdout

1 Comment

bad advice: doesn't exist in py3k, docs say: Using the subprocess module is preferable to using the commands module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.