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.
create process that "ensure" cleaning sub-process
@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)
@cloudhan
Copy link
Author

About try... finally in python https://stackoverflow.com/a/49262664/2091555

What is guaranteed is that if execution flows out of the whole try-finally construct, it will pass through the finally to do so.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment