Python在线编辑器

news/2025/2/5 14:57:48/

python">from flask import Flask, render_template, request, jsonify
import sys
from io import StringIO
import contextlib
import subprocess
import importlib
import threading
import time
import ast
import reapp = Flask(__name__)RESTRICTED_PACKAGES = {'tkinter': '抱歉,在线编译器不支持 tkinter,因为它需要图形界面环境。请在本地运行需要GUI的代码。','tk': '抱歉,在线编译器不支持 tk/tkinter,因为它需要图形界面环境。请在本地运行需要GUI的代码。','pygame': 'pygame将被转换为Web版本运行'  # 不再限制pygame,而是转换它
}def convert_tkinter_to_web(code):"""将tkinter代码转换为Web等效实现"""# 解析Python代码tree = ast.parse(code)# 提取窗口属性window_props = {'title': 'Python GUI','width': '700','height': '500','buttons': [],'labels': [],'entries': [],'layout': []}# 用于存储函数定义functions = {}# 首先收集所有函数定义for node in ast.walk(tree):if isinstance(node, ast.FunctionDef):functions[node.name] = ast.unparse(node)# 分析代码中的tkinter组件for node in ast.walk(tree):if isinstance(node, ast.Assign):if isinstance(node.value, ast.Call):# 提取窗口标题if hasattr(node.value.func, 'attr') and node.value.func.attr == 'Tk':for subnode in ast.walk(tree):if isinstance(subnode, ast.Call) and hasattr(subnode.func, 'attr'):if subnode.func.attr == 'title' and len(subnode.args) > 0:window_props['title'] = ast.literal_eval(subnode.args[0])elif subnode.func.attr == 'geometry' and len(subnode.args) > 0:geom = ast.literal_eval(subnode.args[0])match = re.match(r'(\d+)x(\d+)', geom)if match:window_props['width'] = match.group(1)window_props['height'] = match.group(2)# 提取按钮elif hasattr(node.value.func, 'attr') and node.value.func.attr == 'Button':button = {'text': 'Button', 'command': None}for kw in node.value.keywords:if kw.arg == 'text':button['text'] = ast.literal_eval(kw.value)elif kw.arg == 'command':# 处理不同类型的commandif isinstance(kw.value, ast.Name):# 简单的函数名button['command'] = kw.value.idelif isinstance(kw.value, ast.Lambda):# Lambda表达式button['command'] = f"lambda_{len(window_props['buttons'])}"functions[button['command']] = ast.unparse(kw.value)else:# 其他情况,尝试转换为字符串try:button['command'] = ast.unparse(kw.value)except:button['command'] = 'unknown_command'window_props['buttons'].append(button)# 提取标签elif hasattr(node.value.func, 'attr') and node.value.func.attr == 'Label':label = {'text': ''}for kw in node.value.keywords:if kw.arg == 'text':try:label['text'] = ast.literal_eval(kw.value)except:# 如果不是字面量,尝试直接转换为字符串label['text'] = ast.unparse(kw.value)window_props['labels'].append(label)# 提取输入框elif hasattr(node.value.func, 'attr') and node.value.func.attr == 'Entry':try:entry_id = node.targets[0].idexcept:entry_id = f"entry_{len(window_props['entries'])}"window_props['entries'].append({'id': entry_id})# 生成Web等效代码web_code = f"""
<!DOCTYPE html>
<div class="tk-window" style="width: {window_props['width']}px; height: {window_props['height']}px;"><div class="tk-title-bar">{window_props['title']}</div><div class="tk-content">
"""# 添加标签for label in window_props['labels']:web_code += f'        <div class="tk-label">{label["text"]}</div>\n'# 添加输入框for entry in window_props['entries']:web_code += f'        <input type="text" class="tk-entry" id="{entry["id"]}">\n'# 添加按钮for button in window_props['buttons']:command = button['command'] if button['command'] else ''web_code += f'        <button class="tk-button" onclick="tkButtonClick(\'{command}\')">{button["text"]}</button>\n'web_code += """    </div>
</div>
<script>
window.pythonFunctions = {
"""# 添加Python函数定义for func_name, func_code in functions.items():web_code += f"    '{func_name}': {func_code},\n"web_code += """};
</script>
"""return web_codedef convert_pygame_to_web(code):"""将pygame代码转换为Web Canvas实现"""web_code = """
<canvas id="pygame-canvas" style="border: 1px solid #000;"></canvas>
<script>
const canvas = document.getElementById('pygame-canvas');
const ctx = canvas.getContext('2d');// 设置画布大小
canvas.width = 800;
canvas.height = 600;// 模拟 pygame 的基本功能
const pygame = {display: {set_mode: (size) => {canvas.width = size[0];canvas.height = size[1];return canvas;},update: () => {// Canvas 自动更新},flip: () => {// Canvas 自动更新}},draw: {rect: (surface, color, rect) => {ctx.fillStyle = `rgb(${color[0]},${color[1]},${color[2]})`;ctx.fillRect(rect[0], rect[1], rect[2], rect[3]);},circle: (surface, color, pos, radius) => {ctx.beginPath();ctx.fillStyle = `rgb(${color[0]},${color[1]},${color[2]})`;ctx.arc(pos[0], pos[1], radius, 0, Math.PI * 2);ctx.fill();}},event: {get: () => [],  // 简化的事件处理pump: () => {}},init: () => {},quit: () => {},time: {Clock: function() {return {tick: (fps) => 1000/fps};}}
};// 转换后的Python代码
function runGame() {try {// 这里将插入转换后的游戏代码%PYTHON_CODE%} catch (error) {console.error('Game error:', error);}
}// 启动游戏循环
runGame();
</script>
"""# 处理 Python 代码try:tree = ast.parse(code)# 转换 Python 代码为 JavaScriptjs_code = convert_pygame_code_to_js(tree)web_code = web_code.replace('%PYTHON_CODE%', js_code)return web_codeexcept Exception as e:return f"<div class='error'>转换错误: {str(e)}</div>"def convert_pygame_code_to_js(tree):"""将 Python AST 转换为 JavaScript 代码"""js_code = []for node in ast.walk(tree):if isinstance(node, ast.Import):continue  # 跳过导入语句elif isinstance(node, ast.Assign):# 转换赋值语句if hasattr(node.value, 'func') and isinstance(node.value.func, ast.Attribute):if node.value.func.attr == 'set_mode':js_code.append(f"const screen = pygame.display.set_mode([{node.value.args[0].elts[0].n}, {node.value.args[0].elts[1].n}]);")elif isinstance(node, ast.While):# 转换游戏主循环js_code.append("function gameLoop() {")# ... 处理循环体js_code.append("    requestAnimationFrame(gameLoop);")js_code.append("}")js_code.append("gameLoop();")return "\n".join(js_code)def install_package(package):"""自动安装缺失的包"""# 检查是否是受限制的包if package.lower() in RESTRICTED_PACKAGES:raise ImportError(RESTRICTED_PACKAGES[package.lower()])try:importlib.import_module(package)except ImportError:try:# 尝试使用 pip 安装包subprocess.check_call([sys.executable, "-m", "pip", "install", package])except subprocess.CalledProcessError as e:raise Exception(f"安装包 {package} 失败: {str(e)}")def timeout_handler():"""强制终止超时的代码执行"""raise TimeoutError("代码执行超时(最大执行时间:5秒)")@app.route('/')
def index():return render_template('index.html')@app.route('/execute', methods=['POST'])
def execute_code():code = request.json.get('code', '')try:# 检测是否包含pygame代码if 'pygame' in code:web_code = convert_pygame_to_web(code)return jsonify({'status': 'success','output': '','gui': web_code})# 检测是否包含tkinter代码elif 'tkinter' in code or 'tk' in code:web_code = convert_tkinter_to_web(code)return jsonify({'status': 'success','output': '','gui': web_code})# 非GUI代码正常执行output_buffer = StringIO()with contextlib.redirect_stdout(output_buffer):exec(code, globals(), {})output = output_buffer.getvalue()return jsonify({'status': 'success','output': output if output else '程序执行完成,没有输出'})except Exception as e:return jsonify({'status': 'error','output': f'错误: {str(e)}'})if __name__ == '__main__':app.run(debug=True) 


http://www.ppmy.cn/news/1569534.html

相关文章

「AI学习笔记」深度学习的起源与发展:从神经网络到大数据(二)

深度学习&#xff08;DL&#xff09;是现代人工智能&#xff08;AI&#xff09;的核心之一&#xff0c;但它并不是一夜之间出现的技术。从最初的理论提出到如今的广泛应用&#xff0c;深度学习经历了几乎一个世纪的不断探索与发展。今天&#xff0c;我们一起回顾深度学习的历史…

Redis基础篇(万丈高楼平地起):核心底层数据结构

大家好&#xff0c;我是小龙。近期有很多小伙伴私信我Redis怎么做持久化&#xff1f;集群方案怎么做&#xff1f;分布式锁怎么实现&#xff1f;可是我发现&#xff0c;每次简答完一个问题他还有其他类似问题&#xff0c;或则各个知识点不能串通形成体系&#xff0c;导致很多问题…

windows蓝牙驱动开发-生成和发送蓝牙请求块 (BRB)

以下过程概述了配置文件驱动程序生成和发送蓝牙请求块 (BRB) 应遵循的一般流程。 BRB 是描述要执行的蓝牙操作的数据块。 生成和发送 BRB 分配 IRP。 分配BRB&#xff0c;请调用蓝牙驱动程序堆栈导出以供配置文件驱动程序使用的 BthAllocateBrb 函数。&#xff1b;初始化 BRB…

网络原理一> ip协议相关特性

目录 概述&#xff1a;IP协议结构属性理解&#xff1a;4位版本&#xff1a;4位部首长度&#xff1a;8位服务类型&#xff1a;16位总长度字节数&#xff1a;8位生存时间&#xff1a;8位协议&#xff1a;16位部首检验和&#xff1a;32位源IP地址和32位目的IP地址&#xff1a; IP地…

蓝桥杯嵌入式uart,iic,adc_scan模版

本次用到的是ttl电平 1.波特率配置 2.中断使能 为什么会乱码 //uartmy_main.h #include "my_main.h" uint8_t led_sta0x10; char text[30]; char uart_tx[50]; char uart_rx[50];extern struct Bkeys bkey[]; char passwd[3]{1,2,3}; void LED_Disp(uint8_t dsLED)…

redis教程

Redis 教程 Redis 是一个开源的内存数据结构存储系统&#xff0c;用作数据库、缓存和消息代理。以下是一些基础知识和常用操作。 一、简介 Redis 支持多种数据结构&#xff0c;如字符串、哈希、列表、集合、有序集合等。它具有高性能、高可用性和数据持久化的特性。 二、安…

ros 创建Node

1、使用catkin_create_pkg创建一个软件包 catkin_create_pkg ssr_pkg roscpp rospy std_msgs 2、在软件包的src文件夹下创建一个节点的cpp源码文件 3、在CMakeLists.txt中设置节点源码的编译规则 4.编译运行 编译&#xff1a;shiftctrlB 运行&#xff1a; rosrun ssr_pkg …

AI大模型(二)基于Deepseek搭建本地可视化交互UI

AI大模型&#xff08;二&#xff09;基于Deepseek搭建本地可视化交互UI DeepSeek开源大模型在榜单上以黑马之姿横扫多项评测&#xff0c;其社区热度指数暴涨、一跃成为近期内影响力最高的话题&#xff0c;这个来自中国团队的模型向世界证明&#xff1a;让每个普通人都能拥有媲…