How to read from stdin or from a file if no data is piped in Python?
Argparse allows this to be done in a fairly easy manner, and you really should be using it instead of optparse
unless you have compatibility issues.
The code would go something like this:
import argparseparser = argparse.ArgumentParser()parser.add_argument('--input', type = argparse.FileType('r'), default = '-')
Now you have a parser that will parse your command line arguments, use a file if it sees one, or use standard input if it doesn't.
Process your non-filename arguments however you'd like, so you wind up with an array of non-option arguments, then pass that array as the parameter to fileinput.input()
:
import fileinputfor line in fileinput.input(remaining_args): process(line)
For unix/linux you can detect whether data is being piped in by looking at os.isatty(0)
$ date | python -c "import os;print os.isatty(0)"False$ python -c "import os;print os.isatty(0)"True
I'm not sure there is an equivalent for Windows.
editOk, I tried it with python2.6 on windows XP
C:\Python26>echo "hello" | python.exe -c "import os;print os.isatty(0)" FalseC:\Python26> python.exe -c "import os;print os.isatty(0)" True
So maybe it it not all hopeless for windows