私はh5py
を使用して、Pythonで大きな配列に繰り返し書き出します。かなり長い時間がかかり、コードが実行されている間にファイルサイズが大きくなるのを見ることができます。書き込み処理後にHDF5ファイルの内容が消える
残念ながら、私のpythonプログラムが終了すると、ファイルの内容が消えます。ファイルは破損していませんが、すべての値は0.0
(設定した塗りつぶし値)です。 ファイルf
がf.close()
で閉じられていることを確認してから、ファイルを閉じた後(プログラムを終了する前)、ファイルは元の状態になり、内容はそこに残りました。
誰でもこの動作に精通しており、何が起こるか説明できますか?私は助けていただければ幸いです!
もう少し情報を提供するために、ここで具体的に説明します。 Queue
の結果を処理するProcess
を作成しました。プロセスが初期化されると、HDF5ファイルが作成され、キューの最後の項目に達するとファイルが閉じられます。これらはすべて上手く動作しているようですが、プロセスに関する多くの経験がなく、プロセスクラスのファイル処理が問題になるかどうか疑問に思っています。
from multiprocessing import Process, Queue
import h5py
class ResultProcessor(Process):
def __init__(self, result_queue, result_file):
Process.__init__(self)
self.result_queue = result_queue
self.daemon = True
#open result file handle ('w')
self.f = h5py.File(result_file, 'w')
self.dset = self.f.create_dataset('zipped', (num_jobs, num_subjects), compression="gzip", fillvalue=0)
def run(self):
while True:
next_result = self.result_queue.get()
if next_result is None:
# Poison pill means we should exit
self.f.close()
return
idx, result = next_result
self.dset[idx,:] = result
プロセスは、次に初期化し、以下のように実行されます。ファイルの内容が消えるように見える理由は、これが解決しないだろうが
# results_queue is still empty
result_processor = ResultProcessor(results_queue, file_name)
result_processor.start()
# now the result queue is filled
process_stuff_and_feed_to_result_queue()
# add last queue item so the end can be recognised:
result_queue.put(None)
result_processor.join()
# I checked at this point: The file content is still around!
私が考えることができる唯一の問題は、プロセスの__init__メソッドがメインスレッドで実行されることです。たぶん、hdf5ファイルのオープンをrunメソッドの先頭に移動しますか? – Trilarion