0
我有一個多處理任務,用於處理輸入數據並將結果寫入臨時文件(以備後用)。但是,當我嘗試通過隊列將文件句柄傳輸到父進程時,它會失敗(不會引發異常,但隊列仍爲空)。在Python中通過隊列傳輸文件對象
import multiprocessing, tempfile
def worker(i):
my_data_object = []
my_tmp_file = tempfile.NamedTemporaryFile('wb')
my_tmp_file.write(bytes('Hello world #{}'.format(i), 'utf-8'))
my_tmp_file.seek(0)
queue.put(my_tmp_file)
queue = multiprocessing.Queue()
print('Writing...')
proc = []
for i in range(16):
proc.append(multiprocessing.Process(target = worker, args = (i,)))
proc[i].start()
for p in proc:
p.join()
print('Reading...')
my_strings = []
while True:
try:
tmp_file = queue.get_nowait()
except:
print('All data are read. Queue is now empty')
break
my_strings.append(tmp_file.read())
tmp_file.close()
print('Files content: ', my_strings)
print('Successful termination')
有沒有人知道解決方案?