Since this answer pops up on Google at the top when searching for piping data to a python script
, I'd like to add another method, which I have found in [J. Beazley's Python Cookbook][1] after searching for a less 'gritty' aproach than using sys
. IMO, more pythonic and self-explanatory even to new users.
import fileinput
with fileinput.input() as f_input:
for line in f_input:
print(line, end='')
This approach also works for commands structured like this:
$ ls | ./filein.py # Prints a directory listing to stdout.
$ ./filein.py /etc/passwd # Reads /etc/passwd to stdout.
$ ./filein.py < /etc/passwd # Reads /etc/passwd to stdout.
If you require more complex solutions, you can compine argparse
and fileinput
[as shown in this gist by martinth][2]:
import argparse
import fileinput
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('--dummy', help='dummy argument')
parser.add_argument('files', metavar='FILE', nargs='*', help='files to read, if empty, stdin is used')
args = parser.parse_args()
# If you would call fileinput.input() without files it would try to process all arguments.
# We pass '-' as only file when argparse got no files which will cause fileinput to read from stdin
for line in fileinput.input(files=args.files if len(args.files) > 0 else ('-', )):
print(line)
[1]: https://library.oreilly.com/book/0636920027072/python-cookbook-3rd-edition/199.xhtml?ref=toc#_accepting_script_input_via_redirection_pipes_or_input_files
[2]: https://gist.github.com/martinth/ed991fb8cdcac3dfadf7