Non-blocking file read
<p>How can I read the contents of a binary or a text file in a non-blocking mode?</p>

<p>For binary files: when I <code>open(filename, mode='rb')</code>, I get an instance of <code>io.BufferedReader</code>. The documentation fort <code>io.BufferedReader.read</code> <a href="https://docs.python.org/3.5/library/io.html#io.BufferedReader.read" rel="nofollow">says</a>:</p>

<blockquote>
  <p>Read and return size bytes, or if size is not given or negative, until EOF or if the read call would block in non-blocking mode.</p>
</blockquote>

<p>Obviously a straightforward <code>open(filename, 'rb').read()</code> is in a blocking mode. To my surprise, I could not find an explanation anywhere in the <code>io</code> docs of how to choose the non-blocking mode.</p>

<p>For text files: when I <code>open(filename, mode='rt')</code>, I get <code>io.TextIOWrapper</code>. I assume the relevant docs are those for <code>read</code> in its base class, <code>io.TextIOBase</code>; and <a href="https://docs.python.org/3.5/library/io.html#io.TextIOBase.read" rel="nofollow">according to those docs</a>, there seems no way to do non-blocking read at all:</p>

<blockquote>
  <p>Read and return at most size characters from the stream as a single str. If size is negative or None, reads until EOF.</p>
</blockquote>

<p>I suggest using aiofile. <a href="https://pypi.python.org/pypi/aiofiles/0.2.1" rel="nofollow">https://pypi.python.org/pypi/aiofiles/0.2.1</a></p>

<pre><code>f = yield from aiofiles.open('filename', mode='r')
try:
    contents = yield from f.read()
finally:
    yield from f.close()
print(contents)
'My file contents'
</code></pre>

python python-3.x io