Read from a PIPE of file in Python

in «tip» by Michael Beard
Tags: , , , , ,

Pretty useful to have and know and I always find something, use it, and then forget where I used it (and how) but only remember that I did it. Sigh.

Here are several useful links:

How do I make python programs behave like proper unix tools? - I like ixtmixllix's approach

#!/usr/bin/env python

import argparse, sys

parser = argparse.ArgumentParser()
parser.add_argument('filename', nargs='?')
args = parser.parse_args()
if args.filename:
    string = open(args.filename).read()
elif not sys.stdin.isatty():
    string = sys.stdin.read()
else:
    parser.print_help()

ixtmixllix: The reason why I liked this best is that, as the blogger says, it just outputs a silly message if accidentally called without input. It also slots so nicely into all of my existing Python scripts that I have modified them all to include it.

Pipe output from shell command to a python script

Can I use pipe output as a shell script argument?

What's the best way to tell if a Python program has anything to read from stdin?