refactor: extract code_run header to external file, add subprocess gbk fallback patch

This commit is contained in:
Liang Jiaqing
2026-03-24 09:52:55 +08:00
parent 5643bfb5f0
commit 651e0d2bc8
2 changed files with 19 additions and 2 deletions

16
assets/code_run_header.py Normal file
View File

@@ -0,0 +1,16 @@
import sys, os, json, re, time, subprocess
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'memory'))
_r = subprocess.run
def _d(b):
if not b: return ''
if isinstance(b, str): return b
try: return b.decode()
except: return b.decode('gbk', 'replace')
def _run(*a, **k):
t = k.pop('text', 0) | k.pop('universal_newlines', 0); r = _r(*a, **k)
if t:
if r.stdout is not None: r.stdout = _d(r.stdout)
if r.stderr is not None: r.stderr = _d(r.stderr)
return r
subprocess.run = _run

5
ga.py
View File

@@ -20,8 +20,9 @@ def code_run(code, code_type="python", timeout=60, cwd=None, code_cwd=None, stop
cwd = cwd or os.path.join(script_dir, 'temp'); tmp_path = None
if code_type == "python":
tmp_file = tempfile.NamedTemporaryFile(suffix=".ai.py", delete=False, mode='w', encoding='utf-8', dir=code_cwd)
_mem = os.path.join(script_dir, 'memory')
tmp_file.write(f"import sys, os, json, re, time; sys.path.append(r'{_mem}')\n" + code)
cr_header = os.path.join(script_dir, 'assets', 'code_run_header.py')
if os.path.exists(cr_header): tmp_file.write(open(cr_header, encoding='utf-8').read())
tmp_file.write(code)
tmp_path = tmp_file.name
tmp_file.close()
cmd = [sys.executable, "-X", "utf8", "-u", tmp_path]