如何以非阻塞模式读取二进制或文本文件的内容?在
{{cdi>io.BufferedReader.read
says:
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.
显然,一个简单的open(filename, 'rb').read()
处于阻塞模式。令我惊讶的是,我在io
文档中找不到关于如何选择非阻塞模式的解释。在
对于文本文件:当我open(filename, mode='rt')
时,我得到io.TextIOWrapper
。我假设相关文档是基类中read
的文档,io.TextIOBase
;和{a2},似乎根本没有办法进行非阻塞读取:
Read and return at most size characters from the stream as a single str. If size is negative or None, reads until EOF.
我建议使用aiofile。https://pypi.python.org/pypi/aiofiles/0.2.1
异步样式版本
^{pr2}$文件操作被阻止。没有非阻塞模式。在
但是你可以创建一个线程在后台读取文件。在python3中,^{} module 在这里很有用。在
或者,如果需要在操作完成时调用回调:
^{pr2}$相关问题 更多 >
编程相关推荐