また、ファイルの書き込みを行う別のスレッドを使用Queue
し、すべてのエンティティの記録を保持するために使用します。始めたときは5分でできると思っていたのですが、少し大変でした。simplejson
そして私が知っている他のすべてのそのようなライブラリは部分的な書き込みをサポートしていない[
ので、最初にリストの1つの要素を書き込んだり,
、後で別の要素を追加したりすることはできません]
。次に、各エンティティを個別にダンプします。
(私はあなたのAPIを持っていないので)それをチェックすることができずに、あなたは試すことができます:
import threading
import Queue
import simplejson
from apiWrapper import api
from entities import listEntities #list of the 200,000 entities
CHUNK_SIZE = 1000
class EntityWriter(threading.Thread):
lines_written = False
_filename = "fullEntities.txt"
def __init__(self, queue):
super(EntityWriter, self).__init()
self._q = queue
self.running = False
def run(self):
self.running = True
with open(self._filename,"a") as f:
while True:
try:
entity = self._q.get(block=False)
if not EntityWriter.lines_written:
EntityWriter.lines_written = True
f.write("[")
simplejson.dump(entity,f)
else:
f.write(",\n")
simplejson.dump(entity,f)
except Queue.Empty:
break
self.running = False
def finish_file(self):
with open(self._filename,"a") as f:
f.write("]")
a=api()
fullEntityQueue=Queue.Queue(2*CHUNK_SIZE)
n_entities = len(listEntities)
writer = None
for i, entity in listEntities:
fullEntityQueue.append(a.getFullEntity(entity))
if (i+1) % CHUNK_SIZE == 0 or i == n_entities-1:
if writer is None or not writer.running:
writer = EntityWriter(fullEntityQueue)
writer.start()
writer.join()
writer.finish_file()
このスクリプトの機能
メインループは引き続きエンティティのリストを繰り返し処理し、それぞれの完全な情報を取得します。その後、各エンティティはキューに入れられます。1000エンティティごとに(そしてリストの最後に)、メインスレッドと並行して実行されるEntityWriter-Threadが起動されます。このEntityWriterget
はからQueue
、目的の出力ファイルにダンプします。
上記のように、JSONをリストにするために、いくつかの追加のロジックが[
必要,
です]
。結果のファイルは、原則として、simplejson
リロードするときに理解されるはずです。