支持 input 函数的在线 python 运行环境 - 基于队列

支持 input 函数的在线 python 运行环境 - 基于队列

    • 思路
      • 两次用户输入
      • 三次用户输入
    • 实现
      • 前端使用 vue + element ui
      • Windows 环境的执行器
      • 子进程需要执行的代码
    • 代码仓库
    • 参考

本文提供了一种方式来实现支持 input 函数,即支持用户输的在线 python 运行环境。效果如下图所示:

image-20240104163231417

image-20240104163319674
在这里插入图片描述

思路

  • 前端使用一个数组 input_queue 记录用户从点击运行按钮到现在的所有输入

  • 点击运行按钮时将 codeinput_queue 传给后端

  • 后端将参数传给执行 python 代码的子进程

  • 子进程重写 input() 函数,假设新的实现为 input_wrapper,代码如下,到用户代码运行到 input() 函数时,会执行重写的 input_wrapper(), 在 input_wrapper 中获取到 input_queue,然后使用 input_queue.pop(0) 弹出用户输入最早的信息,如果 input_queue 为空,则说明需要用户输入,通过抛出 InputRequestException 异常的方式通知后端

    def input_wrapper(prompt=''):if input_queue:input_str = input_queue.pop(0)sys.stdout.write(str(prompt) + input_str + "\n")return input_strraise InputRequestException(str(prompt))
    
  • 后端通过处理子进程的标准输出、标准错误,知晓需要用户输入,然后向前端返回以下 json,event.type 为 input_request 代表需要用户输入,prompt 是提示信息

    {"is_timeout": false,"done": false,"event": {"type": "input_request","prompt": "请输入姓名:"}
    }
    
  • 前端弹出弹框提示用户输入,用户输入并点击继续执行按钮时,会将本次的输入追加到 input_queue 的末尾,然后再次调用运行接口,这样循环往复直到程序结束

    image-20240104170040751

在执行以下代码时,可能需要两次用户输入,也可能需要三次。

name = input("请输入姓名:")
print("姓名:", name)if name == "tom":age = input("请输入年龄:")print("年龄:", age)gender = input("请输入性别:")
print("性别:", gender)

两次用户输入

点击运行按钮

请求参数中的 input_queue 为 []{"code": "name = input(\"请输入姓名:\")\nprint(\"姓名:\", name)\n\nif name == \"tom\":\n    age = input(\"请输入年龄:\")\n    print(\"年龄:\", age)\n\ngender = input(\"请输入性别:\")\nprint(\"性别:\", gender)","input_queue": []
}返回值
{"is_timeout": false,"done": false,"event": {"type": "input_request","prompt": "请输入姓名:"}
}

输入 jack

请求参数中的 input_queue 为 ["jack"]{"code": "name = input(\"请输入姓名:\")\nprint(\"姓名:\", name)\n\nif name == \"tom\":\n    age = input(\"请输入年龄:\")\n    print(\"年龄:\", age)\n\ngender = input(\"请输入性别:\")\nprint(\"性别:\", gender)","input_queue": ["jack"]
}返回值
{"is_timeout": false,"done": false,"event": {"type": "input_request","prompt": "请输入性别:"}
}

输入 男

请求参数中的 input_queue 为 ["jack", "男"]
{"code": "name = input(\"请输入姓名:\")\nprint(\"姓名:\", name)\n\nif name == \"tom\":\n    age = input(\"请输入年龄:\")\n    print(\"年龄:\", age)\n\ngender = input(\"请输入性别:\")\nprint(\"性别:\", gender)","input_queue": ["jack","男"]
}返回值
{"is_timeout": false,"done": true,"output": "请输入姓名:jack\r\n姓名: jack\r\n请输入性别:男\r\n性别: 男\r\n"
}

三次用户输入

点击运行按钮

请求参数中的 input_queue 为 []
{"code": "name = input(\"请输入姓名:\")\nprint(\"姓名:\", name)\n\nif name == \"tom\":\n    age = input(\"请输入年龄:\")\n    print(\"年龄:\", age)\n\ngender = input(\"请输入性别:\")\nprint(\"性别:\", gender)","input_queue": []
}返回值
{"is_timeout": false,"done": false,"event": {"type": "input_request","prompt": "请输入姓名:"}
}

输入 tom

请求参数中的 input_queue 为 ["tom"]
{"code": "name = input(\"请输入姓名:\")\nprint(\"姓名:\", name)\n\nif name == \"tom\":\n    age = input(\"请输入年龄:\")\n    print(\"年龄:\", age)\n\ngender = input(\"请输入性别:\")\nprint(\"性别:\", gender)","input_queue": ["tom"]
}返回值
{"is_timeout": false,"done": false,"event": {"type": "input_request","prompt": "请输入年龄:"}
}

输入 18

请求参数中的 input_queue 为 ["tom", "18"]
{"code": "name = input(\"请输入姓名:\")\nprint(\"姓名:\", name)\n\nif name == \"tom\":\n    age = input(\"请输入年龄:\")\n    print(\"年龄:\", age)\n\ngender = input(\"请输入性别:\")\nprint(\"性别:\", gender)","input_queue": ["tom","18"]
}返回值
{"is_timeout": false,"done": false,"event": {"type": "input_request","prompt": "请输入性别:"}
}

输入 男

请求参数中的 input_queue 为 ["tom", "18", "男"]
{"code": "name = input(\"请输入姓名:\")\nprint(\"姓名:\", name)\n\nif name == \"tom\":\n    age = input(\"请输入年龄:\")\n    print(\"年龄:\", age)\n\ngender = input(\"请输入性别:\")\nprint(\"性别:\", gender)","input_queue": ["tom","18","男"]
}返回值
{"is_timeout": false,"done": true,"output": "请输入姓名:tom\r\n姓名: tom\r\n请输入年龄:18\r\n年龄: 18\r\n请输入性别:男\r\n性别: 男\r\n"
}

实现

前端使用 vue + element ui

<!DOCTYPE html>
<html lang="" style="height: 100%;">
<head><meta charset="UTF-8"><link rel="stylesheet" href="./element-ui/index.css"><title>在线 python 执行</title>
</head>
<body style="height: 100%;margin: 0;">
<div id="app" style="height: 98%;width: 98%;padding: 5px"><el-inputtype="textarea":autosize="{ minRows: 10, maxRows: 100}"placeholder="请输入代码"v-model="code"></el-input><el-button type="primary" style="margin-top: 5px;margin-bottom: 5px" @click="exec()">运行</el-button><el-inputtype="textarea":autosize="{ minRows: 10, maxRows: 100}"placeholder="运行结果"v-model="result"></el-input>
</div>
</body>
<script src="./axios.min.js"></script>
<script src="./vue.js"></script>
<script src="./element-ui/index.js"></script>
<script>new Vue({el: '#app',mounted() {},methods: {exec() {const params = {code: this.code,input_queue: this.input_queue}axios.post('http://localhost:8080/exec', params).then(res => {console.log("exec", res)if (res.data.done) {// 执行结束了,需要清空队列this.clearQueue()if (res.data.is_timeout) {// 执行超时this.$message("执行超时");} else {// 正常执行结束this.result = res.data.output}} else {// 执行中,需要用户输入const event = res.data.eventif (event.type === 'input_request') {// 弹框提示用户输入this.$prompt(event.prompt, '输入', {confirmButtonText: '继续执行',cancelButtonText: '终止执行',showClose: false,closeOnClickModal: false,closeOnPressEscape: false}).then(({value}) => {// 继续执行,将本次输入的信息追加进队列,然后再次执行this.input_queue.push(value)this.exec()}).catch((action) => {// 终止执行,需要清空队列console.log("action ", action)this.clearQueue()this.$message("终止执行")});}}})},clearQueue() {this.input_queue = []}},data() {return {code:
`name = input("请输入姓名:")
print("姓名:", name)if name == "tom":age = input("请输入年龄:")print("年龄:", age)gender = input("请输入性别:")
print("性别:", gender)
`,input_queue: [],result: null,}}})</script>
</html>

Windows 环境的执行器

import json
import os
import subprocess
import threading
from threading import Timerimport psutilclass AbstractExecutor:def __init__(self, param):# param 包括 code、input_queueself.param = param# 用于保护 is_timeout 的锁self.lock = threading.Lock()# 是否执行超时了self.is_timeout = Nonedef timeout_callback(self, p: subprocess.Popen):"""执行超时时的回调,会终止执行 python 代码的进程组:param p: 执行 python 代码的进程"""with self.lock:if self.is_timeout is None:self.is_timeout = Trueif self.is_timeout:try:# 终止执行 python 代码的进程组self.terminating_process_group(p)except Exception as e:print("超时回调异常, error: %s", e)def terminating_process_group(self, p: subprocess.Popen):"""终止进程 p 及其子进程:param p: 要终止的进程"""raise NotImplementedError()def create_popen(self) -> subprocess.Popen:"""创建 subprocess.Popen,必须将 stderr 重定向到 stdout"""raise NotImplementedError()def output(self, stdout):if stdout is not None:return stdout.decode("utf-8")else:return ""def execute(self):p = self.create_popen()timer = Timer(3, self.timeout_callback, [p])timer.start()try:# 从标准输入传入 json 参数:code、input_queuep.stdin.write(json.dumps(self.param).encode(encoding="utf-8"))stdout, stderr = p.communicate()with self.lock:if self.is_timeout is None:self.is_timeout = Falsefinally:timer.cancel()return self.is_timeout, self.output(stdout)class WindowsExecutor(AbstractExecutor):__output_prefix = "Active code page: 65001\r\n"def create_popen(self) -> subprocess.Popen:filename = r"D:\project\python\online-python-code-executor\queue-base\exec_py.py"cmd = 'chcp 65001 & set PYTHONIOENCODING=utf-8 & python ' + filename# 将 stderr 重定向到了 stdoutreturn subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,shell=True)def terminating_process_group(self, p: subprocess.Popen):proc_pid = p.pidparent_proc = psutil.Process(proc_pid)for child_proc in parent_proc.children(recursive=True):print(child_proc.pid)child_proc.kill()parent_proc.kill()print(parent_proc.pid)def output(self, stdout):output = super().output(stdout)if output.startswith(self.__output_prefix):return output.removeprefix(self.__output_prefix)else:return outputif os.name == "nt":executor_cls = WindowsExecutordef execute(param):# 执行用户代码is_timeout, stdout = executor_cls(param).execute()if is_timeout:# 执行超时了return {"is_timeout": is_timeout,"done": True,"output": stdout,}else:arr = stdout.split("InputRequestException")if len(arr) > 1:# 需要用户输入return {"is_timeout": is_timeout,"done": False,"event": {"type": "input_request","prompt": arr[-1]}}else:# 正常执行结束return {"is_timeout": is_timeout,"done": True,"output": stdout,}

子进程需要执行的代码

import json
import sysinput_queue = []class InputRequestException(Exception):"""抛出此异常表示需要用户输入"""passdef execute(param):# 重写 input 函数__builtins__.input = input_wrapper# input_queueglobal input_queueinput_queue = param["input_queue"]try:# 执行代码exec(param["code"])except InputRequestException as e:# 如果需要用户输入,则直接退出sys.stdout.write("\n" + "InputRequestException" + e.args[0])exit()def input_wrapper(prompt=''):# 从 input_queue 中弹出if input_queue:input_str = input_queue.pop(0)sys.stdout.write(str(prompt) + input_str + "\n")return input_str# 需要用户输入raise InputRequestException(str(prompt))if __name__ == '__main__':# 从标准输入读取 json 参数:code、input_queuearg = sys.stdin.read()# 执行execute(json.loads(arg))

代码仓库

  • online-python-code-executor/queue-base (github.com)

参考

  • https://pythontutor.com
  • https://github.com/seamile/PyTutor

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/600295.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

什么是谐波减速机?日本Harmonic哈默纳科谐波减速机有哪些优点?

一、什么是谐波减速机&#xff1f; 谐波减速装置最早期被叫做“strain wave gearing”&#xff0c;直译过来为“应变波齿轮”。其后被HarmonicDrive Systems 公司大规模商业实用化后&#xff0c;经过二次翻译后&#xff0c;中文名称才将其称为“谐波齿轮传动”。 谐波减速机是…

Kubernetes(K8s)命令大全

Kubernetes&#xff08;简称K8s&#xff09;是一种开源的容器编排平台&#xff0c;用于自动化应用程序的部署、扩展和管理。通过Kubernetes&#xff0c;您可以轻松地管理容器化应用&#xff0c;实现高可用性、弹性伸缩以及简化的部署和维护。以下是一份Kubernetes常用命令的大全…

数据结构第六弹---带头双向循环链表

双向循环链表 1、带头双向循环链表概念2、带头双向循环链表的优势3、带头双向循环链表的实现3.1、头文件包含和结构定义3.2、创建新结点3.3、打印3.4、初始化3.5、销毁3.6、尾插3.7、头插3.8、头删3.9、尾删3.10、查找3.11、在pos之前插入3.12、删除pos位置3.13、判断是否为空3…

云原生战专题 | 深入浅出分析云原生微服务的技术结构和架构设计

深入浅出分析云原生微服务的技术结构和架构设计 云原生容器技术背景容器编排Kubernetes控制平面的四大组件Kubernetes在容器编排中的设计要点 云原生微服务典型架构第一代微服务架构第二代微服务架构第三代微服务架构第四代微服务架构 未来的云原生架构 — Serverless 云原生容…

springboot + vue3实现增删改查分页操作

springboot vue3实现增删改查分页操作 环境最终实现效果实现功能主要框架代码实现数据库后端前端 注意事项 环境 jdk17 vue3 最终实现效果 实现功能 添加用户&#xff0c;禁用&#xff0c;启用&#xff0c;删除&#xff0c;编辑&#xff0c;分页查询 主要框架 后端 spri…

AJAX(三)跨域

一、同源策略 同源策略最早由Netscape公司提出&#xff0c;是浏览器的一种安全策略。 同源&#xff1a;协议、域名、端口号必须完全相同。&#xff08;同一个来源&#xff09; 违背同源策略就是跨域。 AJAX发送请求时是默认要遵循同源策略的&#xff0c;不是同源策略&#…

pytorch08:学习率调整策略

目录 一、为什么要调整学习率&#xff1f;1.1 class _LRScheduler 二、pytorch的六种学习率调整策略2.1 StepLR2.2 MultiStepLR2.3 ExponentialLR2.4 CosineAnnealingLR2.5 ReduceLRonPlateau2.6 LambdaLR 三、学习率调整小结四、学习率初始化 一、为什么要调整学习率&#xff…

Leetcode2965. 找出缺失和重复的数字

Every day a Leetcode 题目来源&#xff1a;2965. 找出缺失和重复的数字 解法1&#xff1a;哈希 用哈希表统计数组 grid 中各元素的出现次数&#xff0c;其中出现次数为 2 的记为 a。 统计数组 grid 的元素之和为 sum。 数组 grid 其中的值在 [1, n2] 范围内&#xff0c;…

【AWS系列】巧用 G5g 畅游Android流媒体游戏

序言 Amazon EC2 G5g 实例由 AWS Graviton2 处理器提供支持&#xff0c;并配备 NVIDIA T4G Tensor Core GPU&#xff0c;可为 Android 游戏流媒体等图形工作负载提供 Amazon EC2 中最佳的性价比。它们是第一个具有 GPU 加速功能的基于 Arm 的实例。 借助 G5g 实例&#xff0c;游…

06.JAVA常用类方法(StringBuilder与StringBuffer、Arrays与Array比较和常用方法+代码示例)

StringBuilder 基本介绍 概述&#xff1a;可变的字符串类&#xff0c;可视为一个容器&#xff0c;StringBuilder对象中的内容是可变的&#xff0c;也可称之为字符串缓冲类。其常用的成员方法根据有无返回值可以分为查询和删改两大类。 构造方法&#xff1a;StringBuilder( …

阻止持久性攻击改善网络安全

MITRE ATT&CK框架是一个全球可访问的精选知识数据库&#xff0c;其中包含基于真实世界观察的已知网络攻击技术和策略。持久性是攻击者用来访问系统的众多网络攻击技术之一;在获得初始访问权限后&#xff0c;他们继续在很长一段时间内保持立足点&#xff0c;以窃取数据、修改…

Java实战项目六:进销存管理系统

文章目录 一、系统概述二、关键知识点梳理&#xff08;一&#xff09;数据库设计与连接&#xff08;二&#xff09;实体类与关系映射&#xff08;三&#xff09;集合框架的应用&#xff08;四&#xff09;CRUD操作与事务管理 三、系统架构与模块划分&#xff08;一&#xff09;…

集合-及其各种特征详解

集合 概念&#xff1a;是提供一种存储空间 可变 的存储模型&#xff0c;存储的数据容量可以发生改变。&#xff08;也就是集合容量不固定&#xff09; 集合关系图 绿色的代表接口&#xff0c;蓝色的代表接口的实现类 单列集合 Collection(接口) 概述&#xff1a;单列集合的…

spring模块(一)DI依赖注入

一、介绍&#xff1a;Dependency Injection&#xff0c;组件之间依赖关系由容器在运行期决定&#xff0c;形象的说&#xff0c;即由容器动态的将某个依赖关系注入到组件之中。依赖注入的目的并非为软件系统带来更多功能&#xff0c;而是为了提升组件重用的频率&#xff0c;并为…

【策】策略

为应对未来激烈的竞争&#xff0c;需要具备以下要素&#xff1a; 主动选择。每个人都有主动选择的权利&#xff0c;既然做出选择&#xff0c;应对其产生的结果而负责。反逆向思维。梳理过程&#xff0c;分析因果&#xff0c;优化决策。

How to implement anti-crawler strategies to protect site data

How to implement anti-crawler strategies to protect site data 信息校验型反爬虫User-Agent反爬虫Cookie反爬虫签名验证反爬虫WebSocket握手验证反爬虫WebSocket消息校验反爬虫WebSocket Ping反爬虫 动态渲染反爬虫文本混淆反爬虫图片伪装反爬虫CSS偏移反爬虫SVG映射反爬虫字…

VM与欧姆龙PLC通讯设置

1、欧姆龙PLC 进行网口通讯&#xff0c;协议用的Fins tcp&#xff0c;也可以用Fins UDP。 2、主要步骤如下&#xff1b; step1&#xff1a;设置IP地址、端口号默认是9600&#xff0c;根据需要设置寄存器首地址和寄存器数量 step2&#xff1a;鼠标移动到某个地址下&#xff0c…

Python入门-函数

1.函数的定义及调用 函数&#xff1a;函数是将一段实现功能的完整代码&#xff0c;使用函数名称进行封装&#xff0c;通过函数名称进行调用。 以此达到一次编写&#xff0c;多次调用的目的 def get_sum(num): #num叫形式参数s0for i in range(1,num1):siprint(f1到{num}之…

数字后端设计实现 | 数字后端PR工具Innovus中如何创建不同高度的row?

吾爱IC社区星球学员问题&#xff1a;Innovus后端实现时两种种不同高度的site能做在一个pr里面吗&#xff1f; 答案是可以的。 Innovus支持在同一个设计中中使用不同的row&#xff0c;但需要给各自子模块创建power domain。这里所说的不同高度的row&#xff0c;有两种情况。 1…

Docker一键极速安装Nacos,并配置数据库!

1 部署方式 1.1 DockerHub javaedgeJavaEdgedeMac-mini ~ % docker run --name nacos \ -e MODEstandalone \ -e JVM_XMS128m \ -e JVM_XMX128m \ -e JVM_XMN64m \ -e JVM_MS64m \ -e JVM_MMS64m \ -p 8848:8848 \ -d nacos/nacos-server:v2.2.3 a624c64a1a25ad2d15908a67316d…