首页 > 解决方案 > 数组中多个文件的异步处理 - Python

问题描述

我有一个数组,每 5 秒填充一次文件,例如:

my_files = [file1, file2.., filen]

这些文件中的每一个都必须通过函数进行某种处理。例如:

def func1:
    do something 
    return result1

def func2(result1):
    do something else 

等等。这些文件不相关,但是,函数的输出是(例如,第二个函数需要一个函数的结果等)

目前,我的脚本一次处理每个文件,因此它可能会很慢。有没有办法让我的脚本在文件到达时对其进行处理?我对编程很陌生,我无法完全理解异步/并行编程。我已经研究过异步。

标签: pythonarraysasynchronousparallel-processing

解决方案


一般来说,这取决于您的处理方式。在 Python 中,真正的多处理是使用 Multiprocessing 库完成的。另一方面,线程是通过线程库完成的。线程库更像是异步处理。它不会加快您的代码速度,但如果您的代码因等待而变慢,它会很快。

这是你可以做的事情:

import threading
def all_in_one_function(some_file):
  result = process_file(some_file)
  if result == 'result1':
     do this
  if result == 'result2':
     do that


while True:
    if len(my_files) >0:
        file_to_be_processed = my_files.pop()
        threading.Thread(target = all_in_one_function,args=(file_to_be_processed,)).start()
# you pop the files from your array and process it asyncronously, everytime a file appears it will be popped out of array and processed 

就线程而言,我建议您线程一个函数。这意味着,拥有一个可以简单地完成所有处理的功能。或创建将执行处理的类(在函数之间传递参数)并将初始化对象线程化。

我更喜欢创建一个包含所有处理的函数。您不想深入在线程之间传递参数......


推荐阅读