這是你如何把無阻塞上的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()
的可能重複(http://stackoverflow.com/questions/319132/asynchronous-file-writing-possible-in-python) – jcollado 2012-02-13 12:08:26
[異步文件中寫的Python可能嗎?]沒有它沒有,我需要通過使用fcntl來保持簡單:) – Rahul 2012-02-13 14:19:00