How do I make python programs behave like proper unix tools?
Check if a filename is given as an argument, or else read from sys.stdin
.
Something like this:
if sys.argv[1]:
f = open(sys.argv[1])
else:
f = sys.stdin
It's similar to Mikel's answer except it uses the sys
module. I figure if they have it in there it must be for a reason...
Why not just
files = sys.argv[1:]
if not files:
files = ["/dev/stdin"]
for file in files:
f = open(file)
...
My preferred way of doing it turns out to be... (and this is taken from a nice little Linux blog called Harbinger's Hollow)
#!/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()
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.