Python concurrent.futures using subprocess with a callback

故事扮演 提交于 2019-12-05 23:18:26

Ok, now I know what you want and what your problem is.

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 the above code gives output:

$ python3 test.py                                                                                                                                                      
Fortran executed
complete
run_type jid
  1. Using ThreadPool is OK, but ProcessPool is better if fortran_callback is computationally expensive
  2. Callback takes only one parameter which is the future object, so what you need to do is passing parameters via future's attributes.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!