我一直在尝试为python 3上的一系列任务创建一个多处理池。任务如下:1.阅读pdf文件并捕获pdf文件中的表格,然后是- 2.创建一个pickle文件来存储表对象 3. 加载泡菜文件
为了测试目的,我在三个 pdf 文件上以序列化和并行化模式运行了 python 代码。排序是在 200 秒内运行整个过程,并在工作目录中创建泡菜文件。但是,多处理不会在目录中生成泡菜文件,但运行该过程需要 39 秒。
测序代码如下:
os.chdir('C:/Users/dir_path')
def process_table(pdf):
for pdf in pdfs:
tables = camelot.read_pdf(pdf, pages = 'all', flag_size=True, copy_text=['v'], line_scale=40)
print(f'Process {os.getpid()} Processing File Name:{pdf}\nTotal Tables found:{len(tables)}')
with open(pdf.split('.pdf')[0] + '.pkl', 'wb') as f:
pickle.dump(tables, f)
print(f'Process {os.getpid()} Pickle file created for: {pdf}')
with open(pdf.split('.pdf')[0] + '.pkl', 'rb') as g:
pickle.load(g)
print(f'Process {os.getpid()} Pickle file loaded: {pdf}')
def process_handler():
start_time = time.time()
pdfs = [file_name for file_name in os.listdir()]
process_table(pdfs)
end = time.time()
duration = round(time.time() - start_time)
print(f'Whole Process completed in {duration} second(s)')
if __name__ == '__main__':
process_handler()
代码的输出如下:
序列化的输出 多处理的代码如下:
os.chdir('C:/Users/dir_path')
def process_table(pdf):
tables = camelot.read_pdf(pdf, pages = 'all', flag_size=True, copy_text=['v'], line_scale=40)
print(f'Process {os.getpid()} Processing File Name:{pdf}\nTotal Tables found:{len(tables)}')
with open(pdf.split('.pdf')[0] + '.pkl', 'wb') as f:
pickle.dump(tables, f)
print(f'Process {os.getpid()} Pickle file created for: {pdf}')
with open(pdf.split('.pdf')[0] + '.pkl', 'rb') as g:
pickle.load(g)
print(f'Process {os.getpid()} Pickle file loaded for: {pdf}')
def process_handler():
start_time = time.time()
files = [file_name for file_name in os.listdir()]
with ThreadPoolExecutor() as executor:
executor.map(process_table, files)
duration = round(time.time() - start_time)
print(f'Whole Process completed in {duration} second(s)')
if __name__ == '__main__':
process_handler()
我非常感谢您对此的宝贵反馈。这是至关重要的,因为有时 20 MB 的 pdf 文件需要很长时间才能转换为存储在其中的表对象的 pickle 文件。因此,该进程停留在第一个作业(即大小为 20 MB 的 pdf)上,并且在第一个作业完成之前无法移动到下一个作业。
谢谢