14

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?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Abruzzo Forte e Gentile
  • 13,745
  • 25
  • 90
  • 169

5 Answers5

40

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
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
ghostdog74
  • 307,646
  • 55
  • 250
  • 337
9

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]
Pär Wieslander
  • 27,610
  • 7
  • 49
  • 53
1

use subprocess.

SilentGhost
  • 287,765
  • 61
  • 300
  • 288
-1

Use subprocess instead.

Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
-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
sharjeel
  • 5,535
  • 6
  • 33
  • 49
  • bad advice: doesn't exist in py3k, docs say: Using the **`subprocess`** module is preferable to using the commands module. – SilentGhost Jan 20 '10 at 13:23