2026/2/7 20:53:06
网站建设
项目流程
盱眙有做公司网站的吗,做网站一天能赚多少钱,中税网crm客户管理系统,东莞设计兼职网站建设项目概述
Python 在线调试器是一个基于 Web 的 Python 代码执行和调试工具#xff0c;支持在线编写、运行和交互式调试 Python 代码。项目采用前后端分离架构#xff0c;前端负责用户界面和交互#xff0c;后端负责代码执行和调试逻辑。 技术栈
后端技术栈
技术/框架版本…项目概述Python 在线调试器是一个基于 Web 的 Python 代码执行和调试工具支持在线编写、运行和交互式调试 Python 代码。项目采用前后端分离架构前端负责用户界面和交互后端负责代码执行和调试逻辑。技术栈后端技术栈技术/框架版本用途Java17编程语言Spring Boot3.1.5Web框架Spring Web-RESTful API支持Spring Validation-参数验证Jackson-JSON序列化/反序列化Maven3.6项目构建和依赖管理Python3.x代码执行环境核心依赖spring-boot-starter-web: Web开发支持spring-boot-starter-websocket: WebSocket支持预留扩展spring-boot-starter-validation: 参数验证jackson-databind: JSON处理前端技术栈技术/框架版本用途Vue.js3.3.4前端框架Vite5.0.0构建工具和开发服务器CodeMirror 66.x代码编辑器Axios1.6.0HTTP客户端Node.js16运行环境npm-包管理器核心依赖codemirror/lang-python: Python语言支持codemirror/view: 编辑器视图codemirror/state: 编辑器状态管理codemirror/theme-one-dark: 深色主题vitejs/plugin-vue: Vite Vue插件架构设计整体架构┌─────────────────────────────────────────────────────────┐ │ 浏览器 (Browser) │ │ ┌──────────────────────────────────────────────────┐ │ │ │ Vue 3 前端应用 │ │ │ │ ┌──────────────┐ ┌──────────────────┐ │ │ │ │ │ CodeMirror 6 │ │ Axios HTTP │ │ │ │ │ │ 编辑器 │ │ 客户端 │ │ │ │ │ └──────────────┘ └──────────────────┘ │ │ │ └──────────────────────────────────────────────────┘ │ └─────────────────┬───────────────────────────────────────┘ │ HTTP/REST API ┌─────────────────┴───────────────────────────────────────┐ │ Spring Boot 后端 (Port: 8080) │ │ ┌──────────────────────────────────────────────────┐ │ │ │ PythonController │ │ │ │ (REST API 端点) │ │ │ └────────────────┬─────────────────────────────────┘ │ │ │ │ │ ┌────────────────┴─────────────────────────────────┐ │ │ │ PythonExecutionService │ │ │ │ (代码执行和调试逻辑) │ │ │ └────────────────┬─────────────────────────────────┘ │ │ │ │ │ ┌────────────────┴─────────────────────────────────┐ │ │ │ ProcessBuilder Python Process │ │ │ │ (执行Python代码) │ │ │ └────────────────┬─────────────────────────────────┘ │ │ │ │ │ ┌────────────────┴─────────────────────────────────┐ │ │ │ Python 3.x (系统安装) │ │ │ │ - pdb (Python调试器) │ │ │ │ - 代码执行 │ │ │ └──────────────────────────────────────────────────┘ │ └──────────────────────────────────────────────────────────┘分层架构后端分层Controller层 (PythonController) ↓ Service层 (PythonExecutionService) ↓ Process层 (Java ProcessBuilder) ↓ Python运行时环境前端分层视图层 (App.vue Template) ↓ 逻辑层 (App.vue Script - Composition API) ↓ 编辑器层 (CodeMirror 6) ↓ HTTP层 (Axios)核心实现方法1. 代码执行实现1.1 后端实现 (PythonExecutionService.executeCode)核心步骤创建临时文件Path pythonFile Paths.get(tempDir, python_ sessionId .py); Files.write(pythonFile, code.getBytes(UTF-8));启动Python进程ProcessBuilder processBuilder new ProcessBuilder(pythonCmd, pythonFile.toString()); processBuilder.environment().put(PYTHONIOENCODING, utf-8); Process process processBuilder.start();读取输出BufferedReader reader new BufferedReader( new InputStreamReader(process.getInputStream(), UTF-8)); // 设置30秒超时 boolean finished process.waitFor(30, TimeUnit.SECONDS);清理资源Files.deleteIfExists(pythonFile); runningProcesses.remove(sessionId);关键技术点使用ProcessBuilder创建独立的Python进程设置PYTHONIOENCODINGutf-8确保中文输出正确使用临时文件存储用户代码设置执行超时防止死循环UTF-8编码处理确保字符正确传输2. 调试功能实现2.1 断点插入机制实现方法行号映射表构建MapInteger, Integer lineMapping new HashMap(); // 实际行号 - 原始行号断点代码注入// 在断点行之前插入 pdb.set_trace() result.append(indentStr).append(pdb.set_trace() # Breakpoint at line ) .append(originalLineNumber).append(\n);行号映射记录为所有插入的代码行建立映射包括import pdb、空行、pdb.set_trace()等确保能准确还原原始行号2.2 交互式调试会话管理DebugSession 类private static class DebugSession { Process process; // Python进程 BufferedWriter stdin; // 标准输入流发送pdb命令 Path pythonFile; // 临时Python文件 boolean isActive; // 会话是否激活 int currentLine; // 当前执行行号 StringBuilder outputBuffer; // 输出缓冲区 StringBuilder errorBuffer; // 错误缓冲区 MapInteger, Integer lineMapping; // 行号映射表 }会话管理使用ConcurrentHashMap存储多个调试会话支持并发调试多个用户自动清理会话资源2.3 PDB命令映射支持的调试操作操作PDB命令说明继续执行c\ncontinue - 继续到下一个断点单步执行n\nnext - 执行下一行不进入函数步入s\nstep - 进入函数内部步出u\nup - 返回到调用者实现方式String pdbCommand; switch (action) { case continue: pdbCommand c\n; break; case step: pdbCommand s\n; break; case stepOver: pdbCommand n\n; break; case stepOut: pdbCommand u\n; break; } session.stdin.write(pdbCommand); session.stdin.flush();2.4 行号解析和映射PDB输出格式解析// PDB输出格式: /path/to/file.py(行号)function_name() Pattern pattern Pattern.compile(\\s[^\\(]*\\(\\s*(\\d)\\s*\\)[^\n]*);行号转换从PDB输出中提取实际行号通过映射表转换为原始行号如果没有精确匹配向上查找最接近的行号返回给前端显示3. 前端编辑器实现3.1 CodeMirror 6 集成编辑器初始化editorView.value new EditorView({ doc: codeContent, extensions: [ basicSetup, // 基础功能 python(), // Python语言支持 oneDark, // 深色主题 breakpointGutter, // 断点gutter currentLineHighlight // 当前行高亮 ], parent: editorContainer.value })3.2 断点可视化实现原理使用GutterMarker创建断点标记使用StateField管理断点状态使用RangeSet存储断点位置支持点击gutter区域切换断点关键代码// 断点标记类 class BreakpointMarker extends GutterMarker { toDOM() { const span document.createElement(span) span.className breakpoint-marker span.textContent ● return span } } // 断点状态字段 const breakpointState StateField.define({ create() { return RangeSet.empty }, update(breakpoints, tr) { // 处理断点变更 } })3.3 当前行高亮实现方法// 当前行装饰器 const currentLineDecoration Decoration.line({ class: cm-current-line }) // 当前行状态字段 const currentLineState StateField.define({ create() { return RangeSet.empty }, update(currentLine, tr) { // 更新当前行位置 }, provide: f EditorView.decorations.from(f) })样式定义.cm-current-line { background-color: rgba(78, 148, 255, 0.15); outline: 1px solid rgba(78, 148, 255, 0.3); }关键技术点1. 进程管理进程启动使用ProcessBuilder创建独立进程分离标准输出和错误输出设置环境变量确保编码正确进程控制使用Process.waitFor(timeout)实现超时控制使用Process.destroyForcibly()强制终止使用ConcurrentHashMap管理多个进程2. 异步I/O处理输出读取Thread outputThread new Thread(() - { try (BufferedReader reader ...) { String line; while ((line reader.readLine()) ! null session.isActive) { synchronized (session.outputBuffer) { session.outputBuffer.append(line).append(\n); } } } }); outputThread.start();关键点使用独立线程读取进程输出使用同步块保证线程安全实时解析行号并更新状态3. 行号映射算法问题插入import pdb和pdb.set_trace()后行号会偏移PDB显示的是插入后的行号需要转换为原始行号解决方案构建完整的行号映射表精确匹配优先向上查找最接近的行号最多10行如果找不到使用估算方法4. 编码处理UTF-8编码设置// 后端 processBuilder.environment().put(PYTHONIOENCODING, utf-8); Files.write(pythonFile, code.getBytes(UTF-8)); new InputStreamReader(process.getInputStream(), UTF-8) // 前端 // Axios自动处理UTF-8编码配置文件server.servlet.encoding.charsetUTF-8 server.servlet.encoding.enabledtrue server.servlet.encoding.forcetrue spring.http.encoding.charsetUTF-8 spring.http.encoding.enabledtrue spring.http.encoding.forcetrue5. 会话管理会话存储ConcurrentHashMapString, DebugSession debugSessions ConcurrentHashMapString, Process runningProcesses会话生命周期开始调试时创建会话执行调试命令时更新会话调试完成或停止时清理会话自动清理临时文件API接口设计1. 代码执行接口接口POST /api/python/execute请求体{ code: print(Hello, World!), sessionId: session_123 }响应{ output: Hello, World!\n, error: , success: true, sessionId: session_123 }2. 调试接口接口POST /api/python/debug请求体{ code: def func():\n x 10\n return x, sessionId: session_123, breakpoints: [2, 3], action: start | continue | step | stepOver | stepOut }响应{ output: file.py(2)func()\n- x 10, error: , success: true, currentLine: 2, sessionId: session_123 }3. 停止执行接口接口POST /api/python/stop/{sessionId}响应执行已停止调试功能实现原理1. 断点插入流程原始代码 插入后代码 ───────────────── ───────────────── 1 def func(): 1 import pdb 2 x 10 2 3 return x 3 def func(): 4 pdb.set_trace() # Breakpoint at line 2 5 x 10 6 return x 行号映射: 实际行号 - 原始行号 4 - 2 5 - 22. PDB交互流程前端 后端 Python进程 │ │ │ │-- startDebug ----│ │ │ │-- 创建临时文件 -----│ │ │-- 启动进程 ---------│ │ │-- PDB暂停在第N行 ---│ │-- 返回行号N -----│ │ │ │ │ │-- step ----------│ │ │ │-- 发送 s\n -------│ │ │ │-- 步入函数 │ │-- PDB暂停在第M行 ---│ │-- 返回行号M -----│ │3. 行号解析流程PDB输出: file.py(15)func()\n- x 10 ↓ 正则匹配: Pattern.compile(\s[^\(]*\(\s*(\d)\s*\)) ↓ 提取行号: 15 ↓ 查找映射: lineMapping.get(15) 12 ↓ 返回前端: currentLine 12前端交互实现1. Vue 3 Composition API响应式状态const breakpoints ref([]) const currentDebugLine ref(null) const isInDebugMode ref(false)生命周期管理onMounted(() { initEditor() sessionId.value generateSessionId() window.addEventListener(keydown, handleKeyPress) }) onUnmounted(() { window.removeEventListener(keydown, handleKeyPress) })2. 断点管理添加断点const addBreakpoint () { if (newBreakpoint.value newBreakpoint.value 0) { if (!breakpoints.value.includes(lineNum)) { breakpoints.value.push(lineNum) breakpoints.value.sort((a, b) a - b) syncBreakpointsToEditor() } } }断点同步watch(breakpoints, () { nextTick(() { syncBreakpointsToEditor() }) }, { deep: true })3. 调试控制调试命令执行const executeDebugCommand async (action) { const response await axios.post(${API_BASE}/debug, { code: , sessionId: sessionId.value, breakpoints: [], action: action // continue, step, stepOver, stepOut }) // 更新当前行号并高亮 if (result.currentLine) { currentDebugLine.value result.currentLine highlightCurrentLine(result.currentLine) } }键盘快捷键F5: 继续执行F7: 步入F8: 单步执行ShiftF8: 步出4. 实时更新机制当前行高亮更新const highlightCurrentLine (lineNum) { const view editorView.value const line view.state.doc.line(lineNum) view.dispatch({ effects: [ EditorView.scrollIntoView(line.from, { y: center }), setCurrentLineEffect.of(line.from) ] }) }部署方案附代码仓库链接https://gitee.com/ghostmen/python-debug-demo开发环境后端端口8080启动mvn spring-boot:run或使用start-backend.bat/start-backend.sh前端端口3000启动npm run dev或使用start-frontend.bat/start-frontend.shVite代理/api→http://localhost:8080生产环境建议后端打包mvn clean package运行java -jar target/python-debug-backend-1.0.0.jar配置修改application.properties反向代理Nginx前端构建npm run build输出目录dist/静态资源服务器Nginx / Apache或集成到后端静态资源安全建议代码执行限制添加沙箱机制限制系统调用限制资源使用CPU、内存网络安全配置具体的CORS允许域名使用HTTPS添加身份验证输入验证验证代码长度过滤危险操作设置执行超时性能优化1. 进程管理优化限制并发执行的进程数及时清理已完成的进程使用线程池管理I/O操作2. 前端优化代码编辑器懒加载输出内容虚拟滚动大量输出时防抖处理频繁的断点操作3. 缓存策略缓存Python命令检测结果复用调试会话如果可能扩展方案1. WebSocket实时交互优势实时双向通信更好的调试体验支持断点处的变量查看实现方向使用 Spring WebSocket前端使用 WebSocket API实时推送调试状态2. 使用debugpy替代pdb优势更专业的调试协议DAP更好的性能支持更多调试功能实现方向集成debugpy库实现DAP协议客户端支持变量查看、表达式求值等3. 多文件支持实现方向文件管理器组件多标签编辑器文件间依赖管理4. 代码补全实现方向集成Python语言服务器如PyrightCodeMirror自动补全扩展提供代码提示和错误检查技术难点与解决方案难点1: 行号映射准确性问题插入调试代码后行号偏移需要准确映射回原始行号。解决方案建立完整的行号映射表使用向上查找算法作为备选智能匹配最接近的行号难点2: PDB输出解析问题PDB输出格式多样需要准确提取当前行号。解决方案使用正则表达式匹配多种格式从后往前查找最新的PDB提示符容错处理支持多种输出格式难点3: 异步I/O同步问题异步读取输出与同步操作之间的时序问题。解决方案使用同步块保护共享资源合理的等待时间状态标志控制异步读取难点4: 编码问题问题Windows系统默认GBK编码导致中文乱码。解决方案设置PYTHONIOENCODINGutf-8环境变量统一使用UTF-8编码Spring Boot配置UTF-8响应编码总结本项目采用前后端分离架构使用Spring Boot 3.x和Vue 3构建通过ProcessBuilder执行Python代码使用pdb实现交互式调试。核心特点技术选型合理现代化的技术栈易于维护和扩展实现方案可行使用成熟的ProcessBuilder和pdb稳定性好用户体验良好可视化断点、当前行高亮、快捷键支持扩展性强预留WebSocket接口可升级到更专业的调试方案改进方向使用debugpy实现更专业的调试添加WebSocket实现实时交互增强安全性和性能优化支持更多调试功能变量查看、表达式求值等