问题描述
我发现了与我相关的问题,但找不到能解决我问题的问题。
问题
我正在构建一个程序,该程序监视多个目录,然后根据目录或特定文件名生成一个子进程。
这些子流程通常可能需要花费几个小时(例如,如果渲染000个PDF,则需要几个小时)才能完成。因此,我想知道程序最好的方式,即继续监视与仍在运行的子流程并行的文件夹,并能够产生其他子流程,只要它们与子流程的类型不同即可。当前正在运行。
子进程完成后,程序应该能够接收返回代码,该子进程将可以再次运行。
目前的代码
这是当前运行程序的简单代码,当找到文件时调用函数:
while 1:
paths_to_watch = ['/dir1','/dir2','/dir3','/dir4']
after = {}
for x in paths_to_watch:
key = x
after.update({key :[f for f in os.listdir(x)]})
for key,files in after.items():
if(key == '/dir1'):
function1(files)
elif(key == '/dir2'):
function2(files)
elif(key == '/dir3'):
function3(files)
elif(key == '/dir4'):
function3(files)
time.sleep(10)
当然,这意味着程序在继续检查paths_to_watch
中的文件之前会等待该过程完成
从其他问题来看,似乎可以使用进程池来处理,但是我对此领域的知识不足意味着我不知道从哪里开始。
解决方法
我假设您可以使用线程而不是进程,但前提是您的功能function1
和function4
主要受I / O约束。否则,您应在下面的代码中用ProcessPoolExecutor
替换ThreadPoolExecutor
。现在,您的程序会无限循环,因此线程也永远不会终止。我还假设函数function1
至function4
具有唯一的实现。
import os
import time
from concurrent.futures import ThreadPoolExecutor
def function1(files):
pass
def function2(files):
pass
def function3(files):
pass
def function4(files):
pass
def process_path(path,function):
while True:
files = os.listdir(path)
function(files)
time.sleep(10)
def main():
paths_to_watch = ['/dir1','/dir2','/dir3','/dir4']
functions = [function1,function2,function3,function4]
with ThreadPoolExecutor(max_workers=len(paths_to_watch)) as executor:
results = executor.map(process_path,paths_to_watch,functions)
for result in results:
# threads never return so we never get a result
print(result)
if __name__ == '__main__':
main()