<p>经过大量的搜索、尝试和错误之后,我终于想出了如何使用<a href="http://twistedmatrix.com/documents/current/api/twisted.internet.fdesc.html" rel="nofollow">^{<cd1>}</a>。</p>
<pre><code>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))
</code></pre>
<p>[编辑:我也找到了一种不需要使用协议的简单方法]</p>
<pre><code>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)
</code></pre>
<p>要么像这样跑:</p>
<pre><code>react(main, ['/path/to/file'])
</code></pre>