concurrent.futures ThreadPoolExecutor 无法等待



我正在尝试使用concurrent.futures的ThreadPoolExecutor来提高脚本性能。我正在通过 Popen 启动一些外部 python 脚本并将它们封装为未来的对象,但这些对象在完成时进入回调函数,但我可以看到它们在我的机器上运行(它们运行了几分钟)。代码如下所示:

with futures.ThreadPoolExecutor(max_workers=4) as executor: 
        p1 = executor.submit(subprocess.Popen([myotherPythonscript1], stdout = subprocess.PIPE))
        p1.add_done_callback(process_result)
        p2 = executor.submit(subprocess.Popen([myotherPythonscript2], stdout = subprocess.PIPE))
        p2.add_done_callback(process_result)
def process_result( future ):
        logger.info( "Seeding process finished...")

我还尝试了 running() 和 wait() 未来函数的不同方法,但结果相同。将来的对象被标记为已完成,但实际上它们仍在运行。我错过了什么吗?

谢谢

你不能

只将Popen的结果传递给你的执行者,你必须传递一个可调用的。

>>> from concurrent.futures import *
>>> from subprocess import *
>>> executor = ThreadPoolExecutor(4)
>>> future = executor.submit(Popen(['echo', 'test'], stdout=PIPE))
>>> future.exception()
TypeError("'Popen' object is not callable",)

另一方面,这有效:

from concurrent.futures import *
from subprocess import *
def make_call():
    process = Popen(['echo', 'test'], stdout=PIPE)
    return process.communicate()[0]
executor = ThreadPoolExecutor(4)
future = executor.submit(make_call)
print(future.result())

最新更新