OS specific command in Python

Avell Diroll avelldiroll at yahoo.fr
Wed Jun 21 16:34:24 EDT 2006


3c273 wrote:
> I was just trying to learn how to use .communicate() and all of the examples
> I see have [0] after .communicate(). What is the significance of the [0]?


 From the Python Library Reference 
(http://docs.python.org/lib/node239.html), you learn that the method 
communicate() from the subprocess.Popen() class returns a tuple 
containing the standard output as first item and the standard error of 
the child process as second item. So the [0] in the example is for 
selecting the first item of the tuple ...

####

from subprocess import *
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

### is equivalent to :

from subprocess import *
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output_and_error = p2.communicate()
output = output_and_error[0]

### or :

from subprocess import *
p1 = Popen(["dmesg"], stdout=PIPE)
output=Popen(["grep","hda"],stdin=p1.stdout,stdout=PIPE).communicate()[0]

### or :

from subprocess import *
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
(output, stderror) = p2.communicate()


I hope it was useful ...




More information about the Python-list mailing list