经过大量的搜索、试验和错误,我终于想出了如何使用fdesc
.
from __future__ import print_function
from twisted.internet.task import react
from twisted.internet import stdio, protocol
from twisted.internet.defer import Deferred
from twisted.internet.fdesc import readFromFD, setNonBlocking
class FileReader(protocol.Protocol):
def __init__(self, filename):
self.f = open(filename, 'rb')
def dataReceived(self, data):
self.transport.write(data)
def connectionMade(self):
fd = self.f.fileno()
setNonBlocking(fd)
readFromFD(fd, self.dataReceived)
def connectionLost(self, reason):
self.f.close()
def main(reactor, filename):
stdio.StandardIO(FileReader(filename))
[编辑:我也只是想出了一种不需要使用协议的更简单的方法]
def getFile(filename):
with open(filename) as f:
d = Deferred()
fd = f.fileno()
setNonBlocking(fd)
readFromFD(fd, d.callback)
return d
def main(reactor, filename):
d = getFile(filename)
return d.addCallback(print)
像这样运行:
react(main, ['/path/to/file'])