Skip to content

Commit d620613

Browse files
committed
Add rethrow as suggested by ChatGPT
1 parent fe1a174 commit d620613

File tree

1 file changed

+27
-16
lines changed

1 file changed

+27
-16
lines changed

cuda_bindings/tests/run_python_code_safely.py

Lines changed: 27 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -56,14 +56,16 @@ def __call__(self):
5656
pass
5757

5858

59-
def run_in_spawned_child_process(func, *, args=None, kwargs=None, timeout=None):
59+
def run_in_spawned_child_process(func, *, args=None, kwargs=None, timeout=None, rethrow=False):
6060
"""Run `func` in a spawned child process, capturing stdout/stderr.
6161
6262
The provided `func` must be defined at the top level of a module, and must
6363
be importable in the spawned child process. Lambdas, closures, or interactively
6464
defined functions (e.g., in Jupyter notebooks) will not work.
65-
"""
6665
66+
If `rethrow=True` and the child process exits with a nonzero code,
67+
raises ChildProcessError with the captured stderr.
68+
"""
6769
ctx = multiprocessing.get_context("spawn")
6870
result_queue = ctx.Queue()
6971
process = ctx.Process(target=Worker(result_queue, func, args, kwargs))
@@ -74,26 +76,35 @@ def run_in_spawned_child_process(func, *, args=None, kwargs=None, timeout=None):
7476
if process.is_alive():
7577
process.terminate()
7678
process.join()
77-
return CompletedProcess(
79+
result = CompletedProcess(
7880
returncode=PROCESS_KILLED,
7981
stdout="",
8082
stderr=f"Process timed out after {timeout} seconds and was terminated.",
8183
)
82-
83-
try:
84-
returncode, stdout, stderr = result_queue.get(timeout=1.0)
85-
except (queue.Empty, EOFError):
86-
return CompletedProcess(
87-
returncode=PROCESS_NO_RESULT,
88-
stdout="",
89-
stderr="Process exited or crashed before returning results.",
84+
else:
85+
try:
86+
returncode, stdout, stderr = result_queue.get(timeout=1.0)
87+
except (queue.Empty, EOFError):
88+
result = CompletedProcess(
89+
returncode=PROCESS_NO_RESULT,
90+
stdout="",
91+
stderr="Process exited or crashed before returning results.",
92+
)
93+
else:
94+
result = CompletedProcess(
95+
returncode=returncode,
96+
stdout=stdout,
97+
stderr=stderr,
98+
)
99+
100+
if rethrow and result.returncode != 0:
101+
raise ChildProcessError(
102+
f"Child process exited with code {result.returncode}.\n"
103+
f"--- stderr-from-child-process ---\n{result.stderr}"
104+
"<end-of-stderr-from-child-process>\n"
90105
)
91106

92-
return CompletedProcess(
93-
returncode=returncode,
94-
stdout=stdout,
95-
stderr=stderr,
96-
)
107+
return result
97108

98109
finally:
99110
try:

0 commit comments

Comments
 (0)