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)
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)
Read from
sys.stdin
:Being a file-like object, you can use its reading functions or simply iterate over the input lines:
I would use argparse to create an option parser that accepts a file path and opens it.
If
type='open'
does not provide enough control, it can be replaced withargparse.FileType('o')
which acceptsbufsize
andmode
args (see http://docs.python.org/dev/library/argparse.html#type)EDIT: My mistake. This will not support your use case. This will allow you to provide a filepath, but not pipe the file contents into the process. I'll leave this answer here as it might be useful as an alternative.
Using the
fileinput
module would be most appropriate here, and more flexible.http://docs.python.org/library/fileinput.html
In addition to supporting stdin, it can also read from files listed as arguments.