Created
November 25, 2020 06:20
-
-
Save cloudhan/84d7740753a53a022b33261c94a6a321 to your computer and use it in GitHub Desktop.
create process that "ensure" cleaning sub-process
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
About try... finally in python https://stackoverflow.com/a/49262664/2091555