Reputation: 2204
How do we read a file (non-blocking) and print it to the standard output (still non-blocking)? This is the esiest way I can think of but it leaves you with a feeling there must be a better way. Something exposing some LineReceiver - like line by line modification - functionality would be even more preferred.
from twisted.internet import stdio, protocol
from twisted.protocols.basic import FileSender
from twisted.internet import reactor
class FileReader(protocol.Protocol):
def connectionMade(self):
fl = open('myflie.txt', 'rb')
d = FileSender().beginFileTransfer(fl, self.transport)
d.addBoth(fl.close)
d.addBoth(lambda _: reactor.stop())
stdio.StandardIO(FileReader())
reactor.run()
Upvotes: 7
Views: 653
Reputation: 31910
This is a weakness of Twisted. Asynchronous File I/O is hard to do at all, and may be impossible to do "right". There is a ticket that has been open for a long time: https://twistedmatrix.com/trac/ticket/3983 which you may find a useful place to continue this discussion.
The idiom that you're using there is definitely the closest to correct that we currently offer.
Upvotes: 4