Skip to content

Instantly share code, notes, and snippets.

@lquenti
Last active November 18, 2025 11:50
Show Gist options
  • Select an option

  • Save lquenti/e98ff7bac48fbd1998509affedd4eae5 to your computer and use it in GitHub Desktop.

Select an option

Save lquenti/e98ff7bac48fbd1998509affedd4eae5 to your computer and use it in GitHub Desktop.
useful python contexts
import os
from contextlib import contextmanager
@contextmanager
def dir_ctx(path):
original_dir = os.getcwd()
try:
os.chdir(path)
yield
finally:
os.chdir(original_dir)
@contextmanager
def spawn_ctx(args, path, print_output=False, use_sigkill=False, sleep_after=1):
with dir_ctx(path):
proc = subprocess.Popen(
args,
stdout=sys.stdout if print_output else subprocess.DEVNULL,
stderr=sys.stderr if print_output else subprocess.DEVNULL
)
if sleep_after:
time.sleep(sleep_after)
try:
yield proc
finally:
if use_sigkill:
proc.kill()
else:
proc.terminate()
@contextmanager
def spawn_and_wait_ctx(args, path, print_output=False, use_sigkill=False, sleep_after=1):
"""Compared to `spawn_ctx`, this one doesn't terminate, but awaits the process continuation"""
with dir_ctx(path):
proc = subprocess.Popen(
args,
stdout=sys.stdout if print_output else subprocess.DEVNULL,
stderr=sys.stderr if print_output else subprocess.DEVNULL
)
if sleep_after:
time.sleep(sleep_after)
try:
yield proc
finally:
# Wait for completion instead of killing
proc.wait()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment