[Tutor] IPcount = 0 when used with subprocess.call (use something to convert to integer?)

Kushal Kumaran kushal.kumaran+python at gmail.com
Tue May 8 06:28:17 CEST 2012

On Tue, May 8, 2012 at 8:39 AM, Rogelio <scubacuda at gmail.com> wrote:
> I am wrapping a Python wrapper script to "wc -l" (count lines) of a
> list of IP addresses
> *******************************************
> import subprocess
> IPcount = subprocess.call(['wc -l file.txt | awk \'{print $1}\''], shell=True)
> print "You have",IPcount,"IP addresses that are alive."
> *******************************************
> I get the following output
> *******************************************
> 46
> You have 0 IP addresses that are alive.
> *******************************************
> Why does IPcount not equal 46?  Is this what the stout is for?

You can do this:

However, for this simple action of counting lines in a file, I
recommend you do it directly in python:

def count_lines(filename):
    with open(f, 'r') as in_stream:
        return len(in_stream.readlines())

The count_lines function takes a filename and returns the number of
lines in that file.  This way you avoid the problems with shell
metacharacters when using shell=True, mentioned in the subprocess
documentation: http://docs.python.org/py3k/library/subprocess.html#frequently-used-arguments


More information about the Tutor mailing list