用扭曲的文件读取文件到stdout

nev*_*stn 7 python asynchronous twisted

我们如何读取文件(非阻塞)并将其打印到标准输出(仍然是非阻塞的)?这是我能想到的最好的方式,但它让你觉得必须有更好的方法.暴露一些LineReceiver的东西 - 比如逐行修改 - 功能将更加优选.

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()
Run Code Online (Sandbox Code Playgroud)

Gly*_*yph 4

这是 Twisted 的弱点。异步文件 I/O 根本很难做到,而且可能不可能做到“正确”。有一张票已经开放了很长时间:https://twistedmatrix.com/trac/ticket/3983,您可能会找到一个继续讨论的有用地方。

您在那里使用的习语绝对是我们当前提供的最接近正确的习语。