非阻塞文件读取

2024-09-29 01:29:56 发布

您现在位置:Python中文网/ 问答频道 /正文

如何以非阻塞模式读取二进制或文本文件的内容?在

{{cdi>的实例},当{cdi>文件^的时候。文档fort io.BufferedReader.readsays

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.


Tags: orand文档ioreadsizereturnif
2条回答

我建议使用aiofile。https://pypi.python.org/pypi/aiofiles/0.2.1

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

异步样式版本

^{pr2}$

文件操作被阻止。没有非阻塞模式。在

但是你可以创建一个线程在后台读取文件。在python3中,^{} module在这里很有用。在

from concurrent.futures import ThreadPoolExecutor

def read_file(filename):
    with open(filename, 'rb') as f:
        return f.read()

executor = concurrent.futures.ThreadPoolExecutor(1)
future_file = executor.submit(read_file, 'C:\\Temp\\mocky.py')

# continue with other work

# later:

if future_file.done():
    file_contents = future_file.result()

或者,如果需要在操作完成时调用回调:

^{pr2}$

相关问题 更多 >