I want to write to a file using a non-blocking method in Python. On some googling, I found that the language supports fcntl in order to do so, but the method to implement the same is not very clear to me.
This is the code snippet (I don’t know where I am going wrong):
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")
Is this the correct way to perform a non-blocking IO operation on a file? I doubt it. Also, could you suggest any other modules in Python which allow me to do so?
This is how you turn non-blocking mode on for a file in UNIX:
On UNIX, however, turning on non-blocking mode has no visible effect for regular files! Even though the file is in non-blocking mode, the
os.writecall won’t return immediately, it will sleep until the write is complete. To prove it to yourself experimentally, try this:You’ll notice that the
os.writecall does take several seconds. Even though the call is non-blocking (technically, it’s not blocking, it’s sleeping), the call is not asynchronous.AFAIK, there is no way to write to a file asynchronously on Linux or on Windows. You can simulate it, however, using threads. Twisted has a method named
deferToThreadfor this purpose. Here’s how you use it: