我有一个数组,每 5 秒就会填充一次文件,例如:
my_files = [file1, file2.., filen]
这些文件中的每一个都必须通过函数进行某种处理。例如:
def func1:
do something
return result1
def func2(result1):
do something else
等等。这些文件不相关,但是函数的输出是相关的(例如,第二个函数需要一个函数的结果等)
目前,我的脚本一次处理每个文件,因此速度可能相当慢。有没有办法让我的脚本在文件到达时对其进行处理?我在编程方面还很陌生,我不太了解异步/并行编程。我已经研究过 asyncio 了。
最佳答案
一般来说,这取决于您的处理方式。在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
就线程化而言,我建议您对一个函数进行线程化。这意味着,有一个函数可以简单地完成所有处理。或者创建将进行处理的类(在函数之间传递参数)并对初始化的对象进行线程化。
我更喜欢创建一个包含所有处理的函数。 您不想深入在线程之间传递参数......
关于python - 异步处理数组中的多个文件 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54179218/