我目前正在使用启动一个程序subprocess.Popen(cmd, shell=TRUE)
我对 Python 相当陌生,但“感觉”应该有一些 api 可以让我做类似的事情:
subprocess.Popen(cmd, shell=TRUE, postexec_fn=function_to_call_on_exit)
我这样做是为了function_to_call_on_exit
可以根据知道 cmd 已退出来执行某些操作(例如,记录当前正在运行的外部进程的数量)
我假设我可以相当简单地将子进程包装在一个将线程与Popen.wait()
方法,但由于我还没有在 Python 中完成线程处理,而且这似乎对于 API 的存在来说已经足够常见了,所以我想我应该先尝试找到一个。
提前致谢 :)
你是对的 - 没有很好的 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.Thread
with multiprocessing.Process
因为它们遵循(几乎)相同的 API。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)