我构建了一个脚本,该脚本对同一个文本文件进行两个并行处理,每个脚本将结果保存到具有正确文件名的新文本文件中。其中一个过程做得很好,而另一个过程则从问题标题中给出错误消息。
我认为这是因为我将结果保存在缓冲区中,然后将其完全写入文件中,所以我更改了这部分代码,以使生成的每个新结果行都可以立即保存在文件中,但是仍然出错消息仍然出现,所以我无法将结果保存在文件中。
我现在正在测试具有无与伦比的进程的脚本的新版本,但是如何解决这个问题以便使进程保持并行?
下面是示例代码:
from concurrent.futures import ProcessPoolExecutor, as_completed
def process():
counter_object_results = make_data_processing()
txt_file_name = f'file_name.txt'
with open(txt_file_name, 'a') as txt_file:
for count in counter_object_results.items():
txt_file_content = f'{counter_object_results[0]}\t{counter_object_results[1]}\n'
txt_file.write(txt_file_content)
def process_2():
counter_object_results = make_data_processing()
txt_file_name = f'file_name.txt'
with open(txt_file_name, 'a') as txt_file:
for count in counter_object_results.items():
txt_file_content = f'{counter_object_results[0]}\t{counter_object_results[1]}\n'
txt_file.write(txt_file_content)
with ProcessPoolExecutor() as executor:
worker_a = executor.submit(process)
worker_b = executor.submit(process_2)
futures = [worker_a, worker_b]
for worker in as_completed(futures):
resp = worker.result()
print(f'Results saved on {resp}')