Created
          November 25, 2020 06:20 
        
      - 
      
- 
        Save cloudhan/84d7740753a53a022b33261c94a6a321 to your computer and use it in GitHub Desktop. 
Revisions
- 
        cloudhan created this gist Nov 25, 2020 .There are no files selected for viewingThis file contains hidden or 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 charactersOriginal 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)