[英]Tornado PipeIOStream: OSError: [Errno 9] Bad file descriptor
我有一個微型微服務,用於存儲由ID本地標識的消息。 為了確保不會同時寫入文件,我實現了一個隊列。 以下代碼僅工作一次,第二個文件上傳將在下面引發回溯,我真的不知道如何正確處理fd。
from tornado import web, ioloop, gen
from tornado.queues import Queue
from tornado.iostream import PipeIOStream
class Sample:
def __init__(self):
self.queue = Queue()
@gen.coroutine
def write_queue(self):
while True:
item = yield self.queue.get()
print("Message with id %s stored" % item[0])
fd = open(item[0], 'ab')
stream = PipeIOStream(fd.fileno())
yield stream.write(item[1])
stream.close_fd()
class MainHandler(web.RequestHandler):
def initialize(self, store):
self.store = store
@gen.coroutine
def put(self, id):
yield self.store.queue.put((id, self.request.body))
def start(store):
return web.Application([
(r"/(.*)", MainHandler,
{"store": store})
])
if __name__ == '__main__':
store = Store()
app = start(store)
app.listen(8888)
ioloop.IOLoop.current().add_callback(store.write_queue)
ioloop.IOLoop.current().start()
ERROR:tornado.application:Exception in callback functools.partial(<function wrap.<locals>.null_wrapper at 0x7f46657f46a8>, <Future finished exception=OSError(9, 'Bad file descriptor')>)
Traceback (most recent call last):
stream = PipeIOStream(fd.fileno())
File "/usr/local/lib/python3.5/dist-packages/tornado/iostream.py", line 1643, in __init__
self._fio = io.FileIO(self.fd, "r+")
OSError: [Errno 9] Bad file descriptor
open
返回的文件描述符不是管道。 通常,將常規文件與PipeIOStream
一起使用是合法的,但是在Linux上卻沒有用 。 此類文件描述符始終被認為是可讀的,並且從它們讀取或寫入它們始終是塊。 因此,像這樣使用PipeIOStream並不比簡單地執行fd.write(item[1])
。
您已經以只寫模式打開了文件,但是PipeIOStream將其文件包裝在讀/寫包裝器中(我確實感到驚訝,因為實際管道是單向的,所以它曾經工作過)。 我認為這就是異常的來源。 如果您以'ab+'
模式打開文件,我認為它可以工作。 我還沒有嘗試過。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.