Skip to content

Instantly share code, notes, and snippets.

@jepler
Created March 6, 2025 16:57
Show Gist options
  • Save jepler/6c070efeb441b332b097bd903cac3623 to your computer and use it in GitHub Desktop.
Save jepler/6c070efeb441b332b097bd903cac3623 to your computer and use it in GitHub Desktop.
import time
import subprocess
import contextlib
@contextlib.contextmanager
def TerminatingPopen(*args, **kw):
p = subprocess.Popen(*args, **kw)
try:
yield p
finally:
print("exterminate", p.poll())
p.kill() # The harshest way to end the subprocess
print("exterminated?", p.poll())
if __name__ == '__main__':
with TerminatingPopen(["sleep", "60"]) as p:
print(p)
time.sleep(2)
1/0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment