【问题标题】:Asynchronous processing of multiple files in array - Python数组中多个文件的异步处理 - Python
【发布时间】:2019-01-14 10:00:59
【问题描述】:

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

my_files = [file1, file2.., filen]

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

def func1:
    do something 
    return result1

def func2(result1):
    do something else 

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

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

【问题讨论】:

  • 你能把所有函数都放在一个函数里吗?
  • 您的数组是如何准确填充的?另外,什么是最昂贵的操作,是读取文件还是处理其内容?无论如何,您可能想查看concurrent.futures

标签: python arrays asynchronous parallel-processing


【解决方案1】:

一般来说,这取决于您的处理方式。在 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 

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-31
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 2020-10-02
    • 2018-11-10
    • 1970-01-01
    相关资源
    最近更新 更多