Skip to content

Instantly share code, notes, and snippets.

@jadient
Last active August 29, 2015 13:57
Show Gist options
  • Save jadient/9711885 to your computer and use it in GitHub Desktop.
Save jadient/9711885 to your computer and use it in GitHub Desktop.
python wrapper: convert input source to line generator
"""
Convert an input source (file, string, or file descriptor)
into a generator that provides a line at a time.
Online challenges provide input on stdin, but for testing,
it can be useful to provide input via a file or a string.
This wrapper takes any of these formats and returns an
iterator that will provide the input a line at a time.
"""
def input_from_string(data):
""" Input generator, using given data as input """
for line in data.splitlines():
yield line
def input_from_file(file):
""" Input generator, using given file as input """
return input_from_fd(open(file, "r"))
def input_from_fd(fd):
""" Input generator, using given file descriptor as input """
for line in fd:
yield line.rstrip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment