How to make a python script "pipeable" in bash?

gbr picture gbr · Dec 13, 2010 · Viewed 37.8k times · Source

I wrote a script and I want it to be pipeable in bash. Something like:

echo "1stArg" | myscript.py

Is it possible? How?

Answer

khachik picture khachik · Dec 13, 2010

See this simple echo.py:

import sys

if __name__ == "__main__":
    for line in sys.stdin:
        sys.stderr.write("DEBUG: got line: " + line)
        sys.stdout.write(line)

running:

ls | python echo.py 2>debug_output.txt | sort

output:

echo.py
test.py
test.sh

debug_output.txt content:

DEBUG: got line: echo.py
DEBUG: got line: test.py
DEBUG: got line: test.sh