44from 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