Search code examples
pythonshellunixiostdin

Python: How to ensure a program ONLY takes file data from sys.stdin?


I would like to use data from a file called simdata.txt to run a simulation that I wrote in Python. I would like to ensure that when the user executes my program from the command line that the data is only being fed through the sys.stdin stream.

That is, I would like my program to be ran like this:

python3 simulation.py < simdata.txt

as opposed to this (fed through sys.argv as opposed to sys.stdin):

python3 simulation.py simdata.txt

How can I ensure that the user will always execute the program the first way as opposed to the second way? Usually I enforce this rule using this:

if len(sys.argv) > 2:
    print("This is not how you use the program. Example of use:")
    print("python3 simulation.py < simdata.txt")
    exit(1)

But this seems problematic since I may want to add extra flags to my program that would change the behavior of the simulation. That is, maybe I would want to do this:

python3 simulation.py < simdata.txt --plot_data

Is there a better way to ensure that the simdata.txt is only fed through stdin without compromising my ability to add extra program flags?


Solution

  • Working with the argparse module turned out to be the better answer. That way I didn't have to have such strict requirements for input.