1,不太好用
项目结构
app.py
from flask import Flask, render_template, request
import io
import sys
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/execute', methods=['POST'])
def execute():
code = request.form['code']
try:
# 创建一个新的输出流
stdout = io.StringIO()
# 重定向标准输出到新的输出流
sys.stdout = stdout
# 执行Python代码块
exec(code)
# 获取输出结果
output = stdout.getvalue()
return render_template('result.html', output=output)
except Exception as e:
error = str(e)
return render_template('result.html', error=error)
finally:
# 恢复标准输出
sys.stdout = sys.__stdout__
if __name__ == '__main__':
app.run(debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
<title>Python Script Execution</title>
</head>
<body>
<h1>Python Script Execution</h1>
<form action="/execute" method="post">
<textarea name="code" rows="10" cols="50"></textarea>
<br>
<input type="submit" value="Execute">
</form>
</body>
</html>
result.html
<!DOCTYPE html>
<html>
<head>
<title>Execution Result</title>
</head>
<body>
<h1>Execution Result</h1>
{% if output %}
<h2>Output:</h2>
<pre>{{ output }}</pre>
{% elif error %}
<h2>Error:</h2>
<pre>{{ error }}</pre>
{% endif %}
</body>
</html>
测试代码
import pytest
def test_001():
assert 1==1
if __name__ == '__main__':
pytest.main(['-v','test.py'])
示例图
ps: exec(code) 这里修改过pytestcase内容再次执行的结果没有更新,找个时间再研究下
2,推荐这个
20237172253 优化了一下代码
文件结构
app.py
from flask import Flask, render_template, request
import subprocess
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/execute', methods=['POST'])
def execute():
code = request.form['code']
code2 = code
# 将代码块保存到文件中
with open('test_script.py', 'w') as file:
file.write(code2)
# 使用 subprocess 模块运行脚本
result = subprocess.run(['python', 'test_script.py'], capture_output=True, text=True)
# 输出运行结果
print(result.stdout)
return render_template('result.html', output=result.stdout)
if __name__ == '__main__':
app.run()
templates
index.html
<!DOCTYPE html>
<html>
<head>
<title>Python Script Execution</title>
</head>
<body>
<h1>Python Script Execution</h1>
<form action="/execute" method="post">
<textarea name="code" rows="10" cols="50"></textarea>
<br>
<input type="submit" value="Execute">
</form>
</body>
</html>
result.html
<!DOCTYPE html>
<html>
<head>
<title>Execution Result</title>
</head>
<body>
<h1>Execution Result</h1>
{% if output %}
<h2>Output:</h2>
<pre>{{ output }}</pre>
{% elif error %}
<h2>Error:</h2>
<pre>{{ error }}</pre>
{% endif %}
</body>
</html>
示例图