Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Read from stdin or files in Python (combining argparse and fileinput)
import argpase
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)
@drmull

This comment has been minimized.

Copy link

@drmull drmull commented Nov 18, 2016

I found your snippet helpful. But I found out you don't need the if case though, just fileinput.input(args.files) will do, no arguments will make args.files an empty list and and an empty list will make fileinput read from stdin

@andylshort

This comment has been minimized.

Copy link

@andylshort andylshort commented Dec 13, 2019

This really helps if any of your python3 scripts are suffering from a BrokenPipeError or are not being properly handled when you're piping input into a python script you wrote!

@mhashizume

This comment has been minimized.

Copy link

@mhashizume mhashizume commented Feb 12, 2020

Thank you, both this and @drmull's comment were very helpful

@jsf80238

This comment has been minimized.

Copy link

@jsf80238 jsf80238 commented Feb 23, 2020

Thank you, both this and @drmull's comment were very helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment