Skip to content

Instantly share code, notes, and snippets.

@jsheedy
Last active June 16, 2024 15:27
Show Gist options
  • Save jsheedy/ed81cdf18190183b3b7d to your computer and use it in GitHub Desktop.
Save jsheedy/ed81cdf18190183b3b7d to your computer and use it in GitHub Desktop.
Sometimes you need a file-like object when all you have is an iterator, for instance when using psycopg2's cursor.copy_from. This class will handle the impedance mismatch.
import io
import sys
class IteratorFile(io.TextIOBase):
""" given an iterator which yields strings,
return a file like object for reading those strings """
def __init__(self, it):
self._it = it
self._f = io.StringIO()
def read(self, length=sys.maxsize):
try:
while self._f.tell() < length:
self._f.write(next(self._it) + "\n")
except StopIteration as e:
# soak up StopIteration. this block is not necessary because
# of finally, but just to be explicit
pass
except Exception as e:
print("uncaught exception: {}".format(e))
finally:
self._f.seek(0)
data = self._f.read(length)
# save the remainder for next read
remainder = self._f.read()
self._f.seek(0)
self._f.truncate(0)
self._f.write(remainder)
return data
def readline(self):
return next(self._it)
@LuAPi
Copy link

LuAPi commented May 22, 2019

Hi, what's the licence on this file?
If it doesn't have one could you specify one please?
Thanks

@jsheedy
Copy link
Author

jsheedy commented Mar 7, 2020

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to http://unlicense.org/

@jsheedy
Copy link
Author

jsheedy commented Mar 7, 2020

Thanks for asking!

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