import sys
import json
import os
import logging
from io import StringIO
original_stdout = sys.stdout
logs = []
class LogCapture:
def __init__(self, show_logs=False):
self.buffer = StringIO()
self.show_logs = show_logs
def write(self, text):
if text.strip(): logs.append(text.rstrip())
if self.show_logs:
original_stdout.write(text)
def flush(self):
self.buffer.flush()
if self.show_logs:
original_stdout.flush()
sys.stdout = LogCapture(show_logs={{SHOW_LOGS}})
class LoggingHandler(logging.Handler):
def emit(self, record):
msg = self.format(record)
print(f"[{record.levelname}] {msg}")
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
for handler in root_logger.handlers[:]:
root_logger.removeHandler(handler)
handler = LoggingHandler()
handler.setFormatter(logging.Formatter('%(message)s'))
root_logger.addHandler(handler)
args = {}
has_input = False
try:
input_file = os.environ.get('INPUT_JSON_FILE')
if input_file:
with open(input_file, 'r', encoding='utf-8') as f:
input_json = f.read()
args = json.loads(input_json)
has_input = True
print(f"接收到的参数: {args}")
else:
input_json = os.environ.get('INPUT_JSON')
if input_json:
args = json.loads(input_json)
has_input = True
print(f"接收到的参数: {args}")
if has_input and "params" not in args and len(args) > 0:
args["params"] = args.copy()
elif has_input and args.get("params") is None:
args["params"] = {}
except Exception as e:
print(f"解析输入参数失败: {e}")
{{USER_CODE}}
try:
result = None
if 'handler' in globals() and callable(globals()['handler']):
try:
if has_input:
result = handler(args)
else:
result = handler()
if result is None:
print("警告: handler 函数返回了 None")
except Exception as e:
print(f"执行 handler 函数时出错: {e}")
elif 'main' in globals() and callable(globals()['main']):
try:
result = main(args)
except Exception as e:
print(f"执行 main 函数时出错: {e}")
sys.stdout = original_stdout
result_json = None
if result is not None:
if isinstance(result, (dict, list)):
result_json = json.dumps(result)
elif isinstance(result, (int, float, bool)) or result is None:
result_json = result
else:
result_json = str(result)
print(json.dumps({
'logs': logs,
'result': result_json,
'error': None
}))
except Exception as e:
import traceback
error_msg = f"{str(e)}\n{traceback.format_exc()}"
sys.stdout = original_stdout
print(json.dumps({
'logs': logs,
'result': None,
'error': error_msg
}))