2

我正在尝试使用 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() 未来函数的不同方法,但结果相同。未来的对象被标记为已经完成,但实际上它们仍在运行。我错过了什么吗?

谢谢,

4

1 回答 1

5

你不能只将结果传递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())
于 2012-05-14T13:36:47.927 回答