Python子进程: callback when cmd exits

标签 python callback subprocess exit

我目前正在使用 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 的调用替换为 multiprocessing.Process 因为它们遵循(几乎)相同的 API。

关于Python子进程: callback when cmd exits,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2581817/

相关文章:

callback - LuaJIT FFI 回调性能

c - usrsctp数据接收回调参数值变废话

python - ImageMagick 在 Python 子进程中删除元数据时损坏 JPEG 数据

Python:从模式下向mplayer发送命令

python - 命令在终端或程序(Python 和 C++)中给出不同的行为

python - 我的查询不起作用 Postgresql-Python

python - 如何将 .npy 文件转换为 .binaryproto?

python - 如何抓取 dll 消息调度过程并重定向到 python stdout?

python - 解码函数尝试对 Python 进行编码

javascript - jquery 动画回调 - 如何将参数传递给回调