2012-02-13 29 views
13

我想在Python中使用非阻塞方法寫入文件。在一些Google上,我發現語言支持fcntl爲了這樣做,但實現它的方法不是很清楚。如何使用非阻塞IO寫入文件?

這是代碼片段(我不知道我錯了):

import os, fcntl 
nf = fcntl.fcntl(0,fcntl.F_UNCLK) 
fcntl.fcntl(0,fcntl.F_SETFL , nf | os.O_NONBLOCK) 
nf = open ("test.txt", 'a') 
nf.write (" sample text \n") 

這是對文件進行非阻塞IO操作的正確方法是什麼?我對此表示懷疑。另外,你能否建議Python中的其他模塊允許我這樣做?

+0

的可能重複(http://stackoverflow.com/questions/319132/asynchronous-file-writing-possible-in-python) – jcollado 2012-02-13 12:08:26

+0

[異步文件中寫的Python可能嗎?]沒有它沒有,我需要通過使用fcntl來保持簡單:) – Rahul 2012-02-13 14:19:00

回答

14

這是你如何把無阻塞上的UNIX文件方式:

fd = os.open("filename", os.O_CREAT | os.O_WRONLY | os.O_NONBLOCK) 
os.write(fd, "data") 
os.close(fd) 

在UNIX,但是,turning on non-blocking mode has no visible effect for regular files!即使文件處於非阻塞模式,os.write調用也不會立即返回,它將一直處於睡眠狀態直到寫入完成。要將其實驗證明給自己,試試這個:

import os 
import datetime 

data = "\n".join("testing\n" * 10 for x in xrange(10000000)) 
print("Size of data is %d bytes" % len(data)) 

print("open at %s" % str(datetime.datetime.now())) 
fd = os.open("filename", os.O_CREAT | os.O_WRONLY | os.O_NONBLOCK) 
print("write at %s" % str(datetime.datetime.now())) 
os.write(fd, data) 
print("close at %s" % str(datetime.datetime.now())) 
os.close(fd) 
print("end at %s" % str(datetime.datetime.now())) 

你會發現os.write調用不會需要幾秒鐘。即使呼叫是非阻塞的(技術上,它沒有阻塞,它正在睡眠),呼叫是而不是異步。


AFAIK,沒有辦法在Linux或Windows上異步寫入文件。但是,您可以使用線程來模擬它。 Twisted有一個名爲deferToThread的方法用於此目的。這裏是你如何使用它:

from twisted.internet import threads, reactor 

data = "\n".join("testing\n" * 10 for x in xrange(10000000)) 
print("Size of data is %d bytes" % len(data)) 

def blocking_write(): 
    print("Starting blocking_write") 
    f = open("testing", "w") 
    f.write(data) 
    f.close() 
    print("End of blocking_write") 

def test_callback(): 
    print("Running test_callback, just for kicks") 

d = threads.deferToThread(blocking_code) 
reactor.callWhenRunning(cc) 
reactor.run() 
+0

如何從LineReciver或服務器工廠構建的其他此類協議中訪問reactor對象? – Sean 2013-01-11 22:41:04

+0

使用POSIX AIO或Windows IOCP可以對普通文件進行非阻塞式寫入。 – strcat 2014-05-23 08:34:41

4

寫操作由操作系統緩存並在幾秒鐘後轉儲到磁盤。也就是說,他們已經「不擋」了。你不必做任何特別的事情。

+0

如果文件實際上安裝在網絡共享上,該怎麼辦?當然,電話會在收到確認後纔會返回? – Flimm 2012-11-29 20:34:26

+1

取決於遠程文件系統和語義實現,同步或異步。有兩個例子,甚至像「同步關閉」。 – jcea 2012-11-30 01:24:37