import os
from ppio_sandbox.code_interpreter import Sandbox
os.environ["PPIO_API_KEY"] = "YOUR API KEY"
sandbox = Sandbox.create()
print(f"Sandbox created: {sandbox.sandbox_id}")
# 步骤 1:上传应用代码到沙箱
app_code = """\
import logging
import sys
logging.basicConfig(
filename='/home/user/logs/app.log',
level=logging.DEBUG,
format='%(asctime)s [%(levelname)s] %(message)s',
)
logger = logging.getLogger(__name__)
logger.info('Application started')
logger.debug('Loading configuration...')
logger.warning('Memory usage is high')
logger.error('Failed to connect to database')
print('stdout: all tasks completed')
print('stderr: a warning message', file=sys.stderr)
"""
sandbox.commands.run("mkdir -p /home/user/logs")
sandbox.files.write("/home/user/main.py", app_code)
print("Code uploaded to /home/user/main.py")
# 步骤 2:执行应用代码
print("Running application...")
result = sandbox.commands.run("cd /home/user && python3 main.py")
print(f"stdout: {result.stdout}")
print(f"stderr: {result.stderr}")
# 步骤 3:下载日志文件
log_content = sandbox.files.read("/home/user/logs/app.log")
with open("./app.log", "w") as f:
f.write(log_content)
print(f"Log downloaded to ./app.log ({len(log_content)} bytes)")
print("--- Log content ---")
print(log_content)
sandbox.kill()
print("Sandbox destroyed")