2016-10-09 171 views
1

如何在非阻塞模式下讀取二進制文件或文本文件的內容?讀取非阻塞文件

對於二進制文件:當我open(filename, mode='rb'),我得到io.BufferedReader的實例。文檔堡壘io.BufferedReader.readsays

閱讀並返回大小字節,或者如果大小沒有給出或負,直到EOF或者如果讀取調用將在非阻塞模式阻塞。

很明顯,一個簡單的open(filename, 'rb').read()處於阻塞模式。令我驚訝的是,在io關於如何選擇非阻塞模式的文檔中,我找不到任何解釋。

對於文本文件:當我open(filename, mode='rt'),我得到io.TextIOWrapper。我假設相關文檔是read在其基類中的文檔,io.TextIOBase;和according to those docs,似乎根本沒有辦法做到非阻塞讀取:

從流中讀取並返回最多大小字符作爲單個str。如果大小爲負值或無,則讀取直到EOF。

+0

不知道,如果你需要使用在較低水平來做到這一點'os.O_NONBLOCK' –

+0

請告訴我爲什麼低估了我的答案?它不相關嗎? – Juggernaut

+0

@Amin Etesamian我沒有投票,我不確定爲什麼其他讀者不喜歡它。這似乎相關,雖然我不知道aiofiles圖書館。 – max

回答

5

文件操作阻塞。沒有非阻塞模式。

但是你可以創建一個在後臺讀取文件的線程。在Python 3中,concurrent.futures 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() 

或者,如果你需要一個回調函數被調用時,操作完成:

def on_file_reading_finished(future_file): 
    print(future_file.result()) 

future_file = executor.submit(read_file, 'C:\\Temp\\mocky.py') 
future_file.add_done_callback(on_file_reading_finished) 

# continue with other code while the file is loading... 
+0

因此,文檔中對非阻塞模式的引用僅適用於非文件流?是否有文件讀取不能非阻塞的原因? – max