Skip to content

Instantly share code, notes, and snippets.

@cloudhan
Created November 25, 2020 06:20
Show Gist options
  • Save cloudhan/84d7740753a53a022b33261c94a6a321 to your computer and use it in GitHub Desktop.
Save cloudhan/84d7740753a53a022b33261c94a6a321 to your computer and use it in GitHub Desktop.

Revisions

  1. cloudhan created this gist Nov 25, 2020.
    26 changes: 26 additions & 0 deletions clean_process.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    @contextlib.contextmanager
    def clean_process(*args, **kwargs):
    def kill_proc_tree(pid, sig=signal.SIGTERM, include_parent=True, timeout=None, on_terminate=None):
    assert pid != os.getpid(), "won't kill myself"

    try:
    parent = psutil.Process(pid)
    except psutil.NoSuchProcess:
    return

    children = parent.children(recursive=True)
    if include_parent:
    children.append(parent)
    for p in children:
    try:
    p.send_signal(sig)
    except psutil.NoSuchProcess:
    pass
    gone, alive = psutil.wait_procs(children, timeout=timeout, callback=on_terminate)
    return (gone, alive)

    proc = subprocess.Popen(*args, **kwargs)
    try:
    yield proc
    finally:
    kill_proc_tree(proc.pid)