Perl to Python

Tim Hammerquist tim at
Wed Nov 28 02:01:19 CET 2001

Andrew Dalke <dalke at> graced us by uttering:
> Tim Hammerquist:
>>Pipes can be opened using os.popen().  Pipes can be read/written
>>by reading from/writing to the file object returned by
>>os.popen(). Read from this as normal in Python, just as you're
>>reading from the SQL filehandle in the perl code.
>>    # Perl open PIPE, "ls /etc" or die "can't read from pipe:
>>    $!\n"; print while <PIPE>; close PIPE;
>>    # Python (roughly) pipe = os.popen('ls /etc') while 1: line
>>    = pipe.readline() if not line: break print line retval =
>>    pipe.close()
> The Python isn't quite equivalent to the Perl since 'print' adds
> the newline after printing.  You'll either need to chomp off the
> final newline or use sys.stdout.write(line).

Why not just

        print line,


Or you could be really counterintuitive and do:

        print line[:-1] # ;)  (yes, only in *nix/mac)

> Assuming Python 2.2 iterators, this can be written
>   pipe = os.popen('ls /etc')
>   for line in pipe:
>     sys.stdout.write(line)
>   retval = pipe.close()

Is the "for var in fileobj:" syntax new in 2.2? Right on! Thx.

Tim Hammerquist
It has been truly said that hackers have even more words for
equipment failures than Yiddish has for obnoxious people.
    -- Jargon File 4.3.1

More information about the Python-list mailing list