您是对的-没有很好的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。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)