您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python子进程:cmd退出时回调

Python子进程:cmd退出时回调

您是对的-没有很好的API。您也说对了第二点-设计一个使用线程为您执行此操作的函数非常容易。

import threading
import subprocess

def popen_and_call(on_exit, popen_args):
    """
    Runs the given args in a subprocess.Popen, and then calls the function
    on_exit when the subprocess completes.
    on_exit is a callable object, and popen_args is a list/tuple of args that 
    would give to subprocess.Popen.
    """
    def run_in_thread(on_exit, popen_args):
        proc = subprocess.Popen(*popen_args)
        proc.wait()
        on_exit()
        return
    thread = threading.Thread(target=run_in_thread, args=(on_exit, popen_args))
    thread.start()
    # returns immediately after the thread starts
    return thread

甚至线程在Python中都非常容易,但是请注意,如果on_exit()的计算量很大,则需要将其放在单独的进程中,而不是使用多处理(这样GIL不会降低程序速度)。这实际上非常简单- 您基本上可以将所有调用替换为threading.Threadmultiprocessing.Process因为它们遵循(几乎)相同的API。

python 2022/1/1 18:40:09 有296人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶