Python中ProcessPoolExecutor无法正常执行的问题
Python中ProcessPoolExecutor无法正常执行的问题
看起来你的问题出在缺少多进程执行的必要保护机制,尤其是在Windows系统下(如果你用的是Windows的话)。ProcessPoolExecutor依赖多进程实现并行,而Windows没有Linux那样的fork机制,子进程会重新加载整个Python脚本。如果你的代码没有把主逻辑放在if __name__ == "__main__"块里,就会导致子进程重复执行顶层代码,引发一系列问题,比如你现在遇到的只执行部分任务的情况。
我给你修改一下代码,加上必要的保护,同时确保逻辑正确:
from concurrent.futures import ProcessPoolExecutor def checktal1(sheet): print(f"\nchecktal {sheet}\n") return f"Result for {sheet}" def UpdateMongoDB_Cache(username): try: print("Updating MongoDB Cache!") sheets = ["black", "red"] with ProcessPoolExecutor() as executor: # 使用map并行处理sheets results = executor.map(checktal1, sheets) for sheet, result in zip(sheets, results): try: print(f"Processing completed for sheet: {sheet}, result: {result}") except Exception as e: print(f"Error processing sheet {sheet}: {e}") print("Finished Updating MongoDB Cache!") except Exception as e: print(f"General error: {e}") # 关键:把主调用放在这个判断块里 if __name__ == "__main__": # 这里传入你的username参数 UpdateMongoDB_Cache("your_username_here")
为什么这样修改?
if __name__ == "__main__"是Python多进程在Windows下的必备写法,它能防止子进程重新执行主逻辑代码,避免递归创建进程或者执行不必要的代码。- 另外,你的原代码里循环打印的时候没有用到
result,我顺便加上了,方便你看到返回的结果。
你运行修改后的代码,应该就能看到black和red两个sheet的输出了。如果还是有问题,可以检查一下是不是系统的多进程限制,或者有没有其他未捕获的异常(比如可以把外层的except里的错误信息打印得更详细一点)。
备注:内容来源于stack exchange,提问作者kfirwe
相关产品推荐
相关产品推荐

