栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python子进程:cmd退出时回调

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python子进程:cmd退出时回调

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

import threadingimport subprocessdef 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.Thread
multiprocessing.Process
因为它们遵循(几乎)相同的API。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/516687.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号