这是你如何把无阻塞上的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