Abruzzo Forte e Gentile
Abruzzo Forte e Gentile

Reputation: 14869

Parsing a stdout in Python

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?

Upvotes: 18

Views: 57418

Answers (4)

ghostdog74
ghostdog74

Reputation: 342619

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

Upvotes: 41

sharjeel
sharjeel

Reputation: 6005

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

Upvotes: -3

Pär Wieslander
Pär Wieslander

Reputation: 28934

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]

Upvotes: 10

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799082

Use subprocess instead.

Upvotes: -2

Related Questions