Last active
August 29, 2015 13:57
-
-
Save jadient/9711885 to your computer and use it in GitHub Desktop.
python wrapper: convert input source to line generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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