Search code examples
pythoncommand-linepipeargparse

Taking a file or pipe as input


I wish to create a python program that is used from the command line.
It has one positional argument that is a file name.
I want to also be able to pass it input from a pipe

I want to create my python program so that it behaves the same here:

my_program.py input_data.txt

as it does here

cat input_data.txt | my_program.py

I have built programs that do one or the other, but I'm not sure how to conveniently handle both.
I usually use argparse to do this stuff so I was hoping there is an argparse based solution but if not that's fine.


Solution

  • You really shouldn't do this. Get in the habit of redirecting input, and life becomes much better. If you do want to do this, just add a few lines at the start:

    if len(sys.argv) > 1:
        in_file = open(sys.argv[1], 'r')
    else:
        in_file = sys.stdin