Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading file to stdout with twisted

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()
like image 257
neverlastn Avatar asked May 11 '15 11:05

neverlastn


1 Answers

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.

like image 108
Glyph Avatar answered Sep 29 '22 10:09

Glyph