using python on the command line with 'here-documents' and pipes

Nick Craig-Wood nick at craig-wood.com
Mon Nov 15 03:30:11 EST 2004


calmar <calmar at calmar.ws> wrote:
>  echo -e 'line1\nline2\nline3' | python -c '
>  import sys
>  for line in sys.stdin:
>          print line'

The fileinput module is useful, it reads from stdin or from the files
provided on the command line (sys.argv), eg

$ python -c '
import fileinput, sys
for line in fileinput.input():
    # Your code to manipulate line here
    sys.stdout.write(line)
'
This is a line
This is another line
This is a line
This is another line

(The above is (almost) equivalent to perl -pe '# Your code here' BTW
which was in itself derived from the awk usage I think.  The almost
comes in when stdin is from the terminal - you need to press CTRL-D
twice for the python version and once for the perl version)

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list