add python code

This commit is contained in:
2026-06-16 09:35:51 +08:00
parent daecbf4603
commit daf9e50938
17 changed files with 763 additions and 19 deletions
+54
View File
@@ -188,6 +188,60 @@ app.post('/api/run-c', (req, res) => {
}
})
// 运行 Python 代码
app.post('/api/run-py', (req, res) => {
const { code } = req.body
if (!code) {
return res.status(400).json({ error: '请提供 Python 代码' })
}
// 查找 python3 或 python
let pythonCmd = 'python3'
try {
execSync(`${pythonCmd} --version`, { stdio: 'pipe', timeout: 3000 })
} catch {
pythonCmd = 'python'
try {
execSync(`${pythonCmd} --version`, { stdio: 'pipe', timeout: 3000 })
} catch {
return res.status(400).json({
error: '未找到 Python 解释器',
hint: '请安装 Python 3 并确保在 PATH 环境变量中',
installGuide: [
'--- 安装 Python ---',
'1. 访问 https://www.python.org/downloads/ 下载并安装 Python 3',
'2. 安装时勾选 "Add Python to PATH"',
'3. 安装后重启终端',
].join('\n')
})
}
}
const tmpDir = path.join(__dirname, '..', 'tmp')
if (!fs.existsSync(tmpDir)) {
fs.mkdirSync(tmpDir, { recursive: true })
}
const srcFile = path.join(tmpDir, `code_${Date.now()}.py`)
try {
fs.writeFileSync(srcFile, code, 'utf-8')
const output = execSync(`"${pythonCmd}" "${srcFile}"`, {
timeout: 15000,
cwd: tmpDir,
encoding: 'utf-8'
})
res.json({ output })
} catch (runErr) {
res.json({
output: runErr.stdout || runErr.message,
isError: true
})
} finally {
try { if (fs.existsSync(srcFile)) fs.unlinkSync(srcFile) } catch {}
}
})
// 健康检查
app.get('/api/status', (req, res) => {
const compiler = findCompiler()