I have a CLI script and want it to read data from a file. It should be able to read it in two ways :
cat data.txt | ./my_script.py
./my
I'm a noob, so this might not be a good answer, but I'm trying to do the same thing (allow one or more files on the command line, default to STDIN otherwise).
The final combo I put together:
parser = argparse.ArgumentParser()
parser.add_argument("infiles", nargs="*")
args = parser.parse_args()
for line in fileinput.input(args.infiles):
process(line)
This seems like the only way to get all the desired behavior in one elegant package, without requiring named args. Just like unix commands are used as such:
cat file1 file2
wc -l < file1
Not:
cat --file file1 --file file2
Would appreciate feedback/confirmation from veteran idiomatic Pythonistas to make sure I've got the best answer. Haven't seen this complete solution mentioned anywhere else, just fragments.