Search code examples
pythonfilefile-iofilestream

Python command line 'file input stream'


I'm fairly new to python coming from C/C++, I was wondering how I would get my 'main.py' to reconize/use the imput given from a bash shell as:

python main.py < text.txt

(the file is in plain text)


Solution

  • Read from sys.stdin:

    import sys
    sys.stdin.read()
    

    Being a file-like object, you can use its reading functions or simply iterate over the input lines:

    for line in sys.stdin:
        print line