You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让用户访问并使用服务器端运行的代码?

实现远程服务器代码的交互式运行(以PythonAnywhere为例)

方案1:SSH直连运行(付费套餐可用)

  • 要是你的服务器支持SSH(比如PythonAnywhere的付费计划),直接在本地终端敲命令登录:
    ssh 你的用户名@你的服务器地址
  • 登录后切换到代码所在目录,直接运行脚本:
    python3 your_script.py
  • 终端里会实时显示服务器代码的print输出,和本地跑代码完全一样。

方案2:搭个简易Web交互式终端(免费套餐适配)

如果用的是PythonAnywhere免费版,没法用SSH,就用Flask整个简单的Web页面来运行代码:

  1. 先装依赖:pip install flask
  2. 写个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)
  1. 在PythonAnywhere上部署这个Flask应用,用户打开对应的Web地址后,输入代码点“执行”,就能看到print的输出内容。

方案3:用Jupyter Notebook(PythonAnywhere官方支持)

  • 打开PythonAnywhere的控制台,启动Jupyter Notebook,服务器会生成一个可访问的链接。
  • 用户点开链接后,就能像本地用Jupyter一样创建笔记本、写代码、运行,实时看到所有输出,包括print的内容。

内容的提问来源于stack exchange,提问作者Redflame1022

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 19:03:37