Skip to content

Commit 8e9c7b1

Browse files
committed
Factor out class Worker to fix pickle issue.
1 parent b1a5e9d commit 8e9c7b1

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

cuda_bindings/cuda/bindings/_path_finder/run_python_code_safely.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@
44
from io import StringIO
55

66

7-
def run_python_code_safely(python_code, *, timeout=None):
8-
"""Replacement for subprocess.run that forces 'spawn' context"""
9-
ctx = multiprocessing.get_context("spawn")
10-
result_queue = ctx.Queue()
7+
class Worker:
8+
def __init__(self, python_code, result_queue):
9+
self.python_code = python_code
10+
self.result_queue = result_queue
1111

12-
def worker():
12+
def __call__(self):
1313
# Capture stdout/stderr
1414
old_stdout = sys.stdout
1515
old_stderr = sys.stderr
@@ -18,7 +18,7 @@ def worker():
1818

1919
returncode = 0
2020
try:
21-
exec(python_code, {"__name__": "__main__"}) # nosec B102
21+
exec(self.python_code, {"__name__": "__main__"}) # nosec B102
2222
except SystemExit as e: # Handle sys.exit()
2323
returncode = e.code if isinstance(e.code, int) else 0
2424
except Exception: # Capture other exceptions
@@ -32,9 +32,14 @@ def worker():
3232
stderr = sys.stderr.getvalue()
3333
sys.stdout = old_stdout
3434
sys.stderr = old_stderr
35-
result_queue.put((returncode, stdout, stderr))
35+
self.result_queue.put((returncode, stdout, stderr))
36+
3637

37-
process = ctx.Process(target=worker)
38+
def run_python_code_safely(python_code, *, timeout=None):
39+
"""Replacement for subprocess.run that forces 'spawn' context"""
40+
ctx = multiprocessing.get_context("spawn")
41+
result_queue = ctx.Queue()
42+
process = ctx.Process(target=Worker(python_code, result_queue))
3843
process.start()
3944

4045
try:

0 commit comments

Comments
 (0)