Python同期期货使用带有调用的子进程

2024-04-27 18:57:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在执行Python中的FORTRAN exe。FORTRAN exe需要很多分钟才能完成;因此,我需要在exe完成时启动回调。exe不返回任何返回给Python的内容,但在回调函数中,我将使用Python解析FORTRAN中的输出文本文件。在

为此,我使用了concurrent.futuresadd_done_callback(),它很有效。但是web服务的这一部分和我需要一个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"

在提交表单时调用fortran_execute(),我希望返回“fortran executed”,而不等待fortran完成。在

目前Python方法返回时不需要等待FORTRAN完成,但它在返回时也会触发回调。FORTRAN进程继续运行,当它最终完成时,它尝试调用回调函数,并抛出异常,因为future不再存在{}。在

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


Tags: 方法函数adddefcallbackfuturecallexe
1条回答
网友
1楼 · 发布于 2024-04-27 18:57:25

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

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()

运行以上代码给出输出:

^{pr2}$
  1. 使用ThreadPool是可以的,但是如果fortran_callback的计算开销很大,那么ProcessPool就更好了
  2. 回调只接受一个参数,这个参数是未来对象,所以您需要做的是通过future的属性传递参数。在

相关问题 更多 >