One line command line filter

Jon Redgrave jredgrave at capisco.com
Mon Sep 5 16:38:18 EDT 2011


It seems unreasonably hard to write simple one-line unix command line
filters in python:

eg: ls | python -c "<something>  print x.upper()"

to get at sys.stdin or similar needs an import, which makes a
subsequent for-loop illegal.
python -c "import sys; for x in sys.stdin(): print x" <<- SyntaxError

Am I missing something obvious?

The best I've come up with is to use sitecustomize.py to add to
__builtin__
def stdin():
  import sys
  for x in sys.stdin():
    if not x: return
    yield x.strip()
import __builtin__
__builtin__.stdin = stdin

This allows
ls | python -c "for x in stdin(): print x.upper()"

Is there a better solution - if not is this worth a PEP?



More information about the Python-list mailing list