Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a stdout in Python

Tags:

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?

like image 502
Abruzzo Forte e Gentile Avatar asked Jan 20 '10 12:01

Abruzzo Forte e Gentile


People also ask

What is stdout in subprocess python?

stdout: Either a file-like object representing the pipe to be connected to the subprocess's standard output stream using connect_read_pipe() , or the constant subprocess. PIPE (the default). By default a new pipe will be created and connected.

What is parsing in Python?

Parsing is defined as the process of converting codes to machine language to analyze the correct syntax of the code. Python provides a library called a parser.

What is stdout pipe?

Standard output and input. One of the most significant consequences of pipes in Unix is that Unix programs, whenever possible, are designed to read from standard input (stdin) and print to standard output (stdout). These jargony terms refer to streams of data, standardized as plain text.


1 Answers

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
like image 166
ghostdog74 Avatar answered Oct 08 '22 05:10

ghostdog74