Python concurrent.futures 使用带回调的子进程

Fla*_*ash 3 python python-2.7 concurrent.futures

我正在从 Python 执行 FORTRAN exe。FORTRAN exe 需要几分钟才能完成;因此,我需要在 exe 完成时触发回调。exe 不会向 Python 返回任何内容,但在回调函数中,我将使用 Python 来解析 FORTRAN 的输出文本文件。

为此,我正在使用concurrent.futuresand add_done_callback(),并且它有效。但是网络服务的这一部分,我需要有 Python 方法,该方法subprocess.call() / Popen()在执行 FORTRAN exe 后调用返回。然后当 FORTRAN 完成时调用回调函数。

def fortran_callback(run_type, jid):

    return "Fortran finished executing"

def fortran_execute():

    from concurrent.futures import ThreadPoolExecutor as Pool

    args = "fortran.exe arg1 arg2"

    pool = Pool(max_workers=1)
    future = pool.submit(subprocess.call, args, shell=1)
    future.add_done_callback(fortran_callback(run_type, jid))
    pool.shutdown(wait=False)

    return "Fortran executed"
Run Code Online (Sandbox Code Playgroud)

fortran_execute() 在提交表单时被调用,我想在不等待 FORTRAN 完成的情况下返回“Fortran 执行”。

目前,Python 方法无需等待 FORTRAN 完成即可返回,但它也会在返回时触发回调。FORTRAN 进程继续运行,当它最终完成时,它尝试调用回调函数并抛出异常,因为future不再存在TypeError: 'NoneType' object is not callable

我在这里缺少什么来启动 exe subprocess,让函数返回,然后只有在 exe 完成执行时才调用回调方法?

lai*_*e9m 5

好的,现在我知道你想要什么以及你的问题是什么。

def fortran_callback(future):
    print(future.run_type, future.jid)
    return "Fortran finished executing"

def fortran_execute():

    from concurrent.futures import ProcessPoolExecutor as Pool

    args = "sleep 2; echo complete"

    pool = Pool(max_workers=1)
    future = pool.submit(subprocess.call, args, shell=1)
    future.run_type = "run_type"
    future.jid = "jid"
    future.add_done_callback(fortran_callback)

    print("Fortran executed")


if __name__ == '__main__':
    import subprocess
    fortran_execute()
Run Code Online (Sandbox Code Playgroud)

运行上面的代码给出输出:

$ python3 test.py                                                                                                                                                      
Fortran executed
complete
run_type jid
Run Code Online (Sandbox Code Playgroud)
  1. 使用 ThreadPool 没问题,但如果fortran_callback计算成本高,则 ProcessPool 更好
  2. Callback 只接受一个参数,即 future 对象,因此您需要做的是通过future的属性传递参数。