Skip to content

Commit 3eff896

Browse files
refactor: change print to sys.stdout.
1 parent f5feddf commit 3eff896

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

apps/common/utils/tool_code.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ def exec_code(self, code_str, keywords, function_name=None):
8383
set_run_user = f'os.setgid({pwd.getpwnam(_run_user).pw_gid});os.setuid({pwd.getpwnam(_run_user).pw_uid});' if _enable_sandbox else ''
8484
_exec_code = f"""
8585
try:
86-
import os, sys, json, base64, builtins
86+
import os, sys, json
8787
path_to_exclude = ['/opt/py3/lib/python3.11/site-packages', '/opt/maxkb-app/apps']
8888
sys.path = [p for p in sys.path if p not in path_to_exclude]
8989
sys.path += {python_paths}
@@ -97,10 +97,13 @@ def exec_code(self, code_str, keywords, function_name=None):
9797
for local in locals_v:
9898
globals_v[local] = locals_v[local]
9999
exec_result=f(**keywords)
100-
builtins.print("\\n{_id}:"+base64.b64encode(json.dumps({success}, default=str).encode()).decode(), flush=True)
100+
sys.stdout.write("\\n{_id}:")
101+
json.dump({success}, sys.stdout, default=str)
101102
except Exception as e:
102103
if isinstance(e, MemoryError): e = Exception("Cannot allocate more memory: exceeded the limit of {_process_limit_mem_mb} MB.")
103-
builtins.print("\\n{_id}:"+base64.b64encode(json.dumps({err}, default=str).encode()).decode(), flush=True)
104+
sys.stdout.write("\\n{_id}:")
105+
json.dump({err}, sys.stdout, default=str)
106+
sys.stdout.flush()
104107
"""
105108
maxkb_logger.debug(f"Sandbox execute code: {_exec_code}")
106109
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=True) as f:
@@ -114,7 +117,7 @@ def exec_code(self, code_str, keywords, function_name=None):
114117
if not result_line:
115118
maxkb_logger.error("\n".join(lines))
116119
raise Exception("No result found.")
117-
result = json.loads(base64.b64decode(result_line[-1].split(":", 1)[1]).decode())
120+
result = json.loads(result_line[-1].split(":", 1)[1])
118121
if result.get('code') == 200:
119122
return result.get('data')
120123
raise Exception(result.get('msg'))

0 commit comments

Comments
 (0)