如何让用户访问并使用服务器端运行的代码?
实现远程服务器代码的交互式运行(以PythonAnywhere为例)
方案1:SSH直连运行(付费套餐可用)
- 要是你的服务器支持SSH(比如PythonAnywhere的付费计划),直接在本地终端敲命令登录:
ssh 你的用户名@你的服务器地址 - 登录后切换到代码所在目录,直接运行脚本:
python3 your_script.py - 终端里会实时显示服务器代码的
print输出,和本地跑代码完全一样。
方案2:搭个简易Web交互式终端(免费套餐适配)
如果用的是PythonAnywhere免费版,没法用SSH,就用Flask整个简单的Web页面来运行代码:
- 先装依赖:
pip install flask - 写个Flask应用(比如命名为
app.py):
from flask import Flask, render_template_string, request import subprocess import tempfile import os app = Flask(__name__) # 前端页面模板 PAGE_TEMPLATE = """ <!DOCTYPE html> <html> <head> <title>远程代码运行工具</title> </head> <body> <h3>输入代码并运行</h3> <form method="post"> <textarea name="code" rows="10" cols="80">print('hello world')</textarea><br> <button type="submit">执行代码</button> </form> {% if output %} <h4>输出结果:</h4> <pre>{{ output }}</pre> {% endif %} </body> </html> """ @app.route('/', methods=['GET', 'POST']) def run_code(): output = "" if request.method == 'POST': code_content = request.form.get('code', '') # 用临时文件存代码再运行 with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f: f.write(code_content) temp_file = f.name # 执行代码并捕获输出 result = subprocess.run(['python3', temp_file], capture_output=True, text=True) output = result.stdout + result.stderr # 删除临时文件 os.unlink(temp_file) return render_template_string(PAGE_TEMPLATE, output=output) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
- 在PythonAnywhere上部署这个Flask应用,用户打开对应的Web地址后,输入代码点“执行”,就能看到
print的输出内容。
方案3:用Jupyter Notebook(PythonAnywhere官方支持)
- 打开PythonAnywhere的控制台,启动Jupyter Notebook,服务器会生成一个可访问的链接。
- 用户点开链接后,就能像本地用Jupyter一样创建笔记本、写代码、运行,实时看到所有输出,包括
print的内容。
内容的提问来源于stack exchange,提问作者Redflame1022
相关产品推荐
相关产品推荐

