ten sposób można włączyć bez blokowania na tryb dla pliku w systemie UNIX:
fd = os.open("filename", os.O_CREAT | os.O_WRONLY | os.O_NONBLOCK)
os.write(fd, "data")
os.close(fd)
W systemie UNIX, jednak turning on non-blocking mode has no visible effect for regular files! Mimo że plik jest w trybie bez blokowania, wywołanie os.write
nie nastąpi natychmiast, będzie ono działać do momentu zakończenia zapisu. Aby udowodnić to do siebie, eksperymentalnie, spróbuj tego:
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()))
Zauważysz, że wezwanie os.write
ma potrwać kilka sekund. Mimo że połączenie nie jest blokujące (technicznie, nie blokuje, nie śpi), wywołanie jest niesynchroniczne , a nie.
AFAIK, nie ma sposobu na asynchroniczne zapisanie pliku w systemie Linux lub Windows. Możesz go jednak zasymulować za pomocą wątków. Twisted ma w tym celu metodę o nazwie deferToThread
. Oto jak go używać:
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()
możliwe duplikat (http://stackoverflow.com/questions/319132/asynchronous-file-writing-possible-in-python) – jcollado
[Asynchronous pliku pisania możliwie w python?] Nie, nie, muszę to proste, po prostu za pomocą fcntl :) – Rahul