Python subprocess: callback when cmd exits

后端 未结 7 1598
暗喜
暗喜 2020-11-28 21:36

I\'m currently launching a programme using subprocess.Popen(cmd, shell=TRUE)

I\'m fairly new to Python, but it \'feels\' like there ought to be some api

相关标签:
7条回答
  • 2020-11-28 22:39

    There is concurrent.futures module in Python 3.2 (available via pip install futures for older Python < 3.2):

    pool = Pool(max_workers=1)
    f = pool.submit(subprocess.call, "sleep 2; echo done", shell=True)
    f.add_done_callback(callback)
    

    The callback will be called in the same process that called f.add_done_callback().

    Full program

    import logging
    import subprocess
    # to install run `pip install futures` on Python <3.2
    from concurrent.futures import ThreadPoolExecutor as Pool
    
    info = logging.getLogger(__name__).info
    
    def callback(future):
        if future.exception() is not None:
            info("got exception: %s" % future.exception())
        else:
            info("process returned %d" % future.result())
    
    def main():
        logging.basicConfig(
            level=logging.INFO,
            format=("%(relativeCreated)04d %(process)05d %(threadName)-10s "
                    "%(levelname)-5s %(msg)s"))
    
        # wait for the process completion asynchronously
        info("begin waiting")
        pool = Pool(max_workers=1)
        f = pool.submit(subprocess.call, "sleep 2; echo done", shell=True)
        f.add_done_callback(callback)
        pool.shutdown(wait=False) # no .submit() calls after that point
        info("continue waiting asynchronously")
    
    if __name__=="__main__":
        main()
    

    Output

    $ python . && python3 .
    0013 05382 MainThread INFO  begin waiting
    0021 05382 MainThread INFO  continue waiting asynchronously
    done
    2025 05382 Thread-1   INFO  process returned 0
    0007 05402 MainThread INFO  begin waiting
    0014 05402 MainThread INFO  continue waiting asynchronously
    done
    2018 05402 Thread-1   INFO  process returned 0
    
    0 讨论(0)
提交回复
热议问题