Skip to content

Commit ff5150d

Browse files
refactor: redirect stdout.
1 parent b639061 commit ff5150d

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

apps/common/utils/tool_code.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ def exec_code(self, code_str, keywords, function_name=None):
8282
_exec_code = f"""
8383
try:
8484
import os, sys, json
85+
from contextlib import redirect_stdout
8586
path_to_exclude = ['/opt/py3/lib/python3.11/site-packages', '/opt/maxkb-app/apps']
8687
sys.path = [p for p in sys.path if p not in path_to_exclude]
8788
sys.path += {python_paths}
@@ -90,18 +91,18 @@ def exec_code(self, code_str, keywords, function_name=None):
9091
globals_v={{}}
9192
{set_run_user}
9293
os.environ.clear()
93-
exec({dedent(code_str)!a}, globals_v, locals_v)
94-
f_name, f = {action_function}
95-
for local in locals_v:
96-
globals_v[local] = locals_v[local]
97-
exec_result=f(**keywords)
94+
with redirect_stdout(open(os.devnull, 'w')):
95+
exec({dedent(code_str)!a}, globals_v, locals_v)
96+
f_name, f = {action_function}
97+
globals_v.update(locals_v)
98+
exec_result=f(**keywords)
9899
sys.stdout.write("\\n{_id}:")
99100
json.dump({{'code':200,'msg':'success','data':exec_result}}, sys.stdout, default=str)
100101
except Exception as e:
101102
if isinstance(e, MemoryError): e = Exception("Cannot allocate more memory: exceeded the limit of {_process_limit_mem_mb} MB.")
102103
sys.stdout.write("\\n{_id}:")
103104
json.dump({{'code':500,'msg':str(e),'data':None}}, sys.stdout, default=str)
104-
sys.stdout.flush()
105+
sys.stdout.flush()
105106
"""
106107
maxkb_logger.debug(f"Sandbox execute code: {_exec_code}")
107108
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=True) as f:

0 commit comments

Comments
 (0)