이 당신이 설정하는 방법입니다 비 차단 UNIX에있는 파일에 모드 :
UNIX에
fd = os.open("filename", os.O_CREAT | os.O_WRONLY | os.O_NONBLOCK)
os.write(fd, "data")
os.close(fd)
그러나 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
[파이썬에서 가능 쓰기 비동기 파일?] 아니오, 그냥 fcntl을 사용하여 간단하게 유지해야합니다 :) – Rahul