perl to python

Scott Schwartz "schwartz+ at usenet " at bio.cse.psu.edu
Wed May 12 15:07:51 EDT 2004


Duncan Booth <me at privacy.net> writes:
> import sys
> for line in sys.stdin:
>     line = line[:-1].split('\t')
>     print "%s %s %s %s" % (line[3], line[2], line[1], line[0])

> While I agree with you that using the appropriate tool is preferred over 
> using Python for everything, I don't really see much to choose between the 
> Python and awk versions here.

1) Python throws an error if you have less than three fields,
requiring more typing to get the same effect.

2) Python generators on stdin behave strangely.  For one thing,
they're not properly line buffered, so you don't get any lines until
eof.  But then, eof is handled wrongly, and the loop doesn't exit.

3) There is no efficient RS equivalent, in case you need to read
paragraphs.

The simpler example

   for line in sys.stdin:
      print line

demonstrates the problem nicely.

$ python z
a
b
c
^D
a
 
b
 
c
 
foo
bar
baz
^D
foo
 
bar
 
baz
^D
^D
$ 

Explanations in the docs about buffering and readahead don't excuse
this poor result.  

$ awk '{print}'
a
a
b
b
c
c
^D
$



More information about the Python-list mailing list