Last active
November 18, 2025 11:50
-
-
Save lquenti/e98ff7bac48fbd1998509affedd4eae5 to your computer and use it in GitHub Desktop.
useful python contexts
This 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 characters
| 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