Hi,
I have a CLI script and want him to read data from a file. It should be able to read it in two ways :
cat data.txt | ./my_script.py
./my_script.py data.txt
A bit like grep, for example.
What I know:
sys.argv
andoptparse
let me read any args and options easily.sys.stdin
let me read data piped infileinput
make the full process automatic
Unfortunetly:
- using
fileinput
use stdin and any args as input. So I can't use options that are not filenames as it tries to open them. sys.stdin.readlines()
work fine, but it I don't pipe any data, it hangs until I enter Ctrl + D- I don't know how to implement "if nothing in stdin, read from a file in args" because stdin is always True in a boolean context.
I'd like a portable way to do so is possible.