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

如何通过浏览器运行上传至VPS服务器的Python Hello World脚本?

解决Python脚本在浏览器中直接显示代码而非执行的问题

问题的核心是Web服务器默认将.py文件当作静态文本返回,没有调用Python解释器执行脚本。以下是具体解决步骤:

通用基础配置

  • 添加Shebang行:在hello.py的第一行添加,告诉服务器使用Python 3解释器执行脚本:
    #!/usr/bin/env python3
    
  • 设置可执行权限:通过SSH登录服务器,给脚本添加执行权限:
    chmod +x /path/to/your/hello.py
    
  • 调整脚本输出格式:浏览器需要合法的HTTP响应,所以脚本要先输出HTTP头,再输出内容:
    #!/usr/bin/env python3
    print("Content-Type: text/html")
    print()  # 空行分隔HTTP头和内容
    print("Hello World")
    

针对Apache服务器的配置

  1. 启用CGI模块:
    # Ubuntu/Debian系统
    a2enmod cgi
    # CentOS/RHEL系统
    httpd -t -D DUMP_MODULES | grep cgi # 先检查是否已启用,未启用则编辑httpd.conf添加LoadModule cgi_module modules/mod_cgi.so
    
  2. 配置脚本识别规则:
    • 方法一:在网站根目录创建.htaccess文件,添加以下内容:
      AddHandler cgi-script .py
      Options +ExecCGI
      
    • 方法二:修改Apache虚拟主机配置文件,在对应Directory段添加:
      <Directory /path/to/your/webroot>
          AddHandler cgi-script .py
          Options +ExecCGI
          AllowOverride All
      </Directory>
      
  3. 重启Apache服务:
    # Ubuntu/Debian
    systemctl restart apache2
    # CentOS/RHEL
    systemctl restart httpd
    

针对Nginx服务器的配置

Nginx本身不处理CGI,需配合fcgiwrap实现:

  1. 安装fcgiwrap:
    # Ubuntu/Debian
    apt install fcgiwrap
    # CentOS/RHEL
    yum install fcgiwrap
    
  2. 修改Nginx站点配置文件,在对应server块中添加:
    location ~ \.py$ {
        root /path/to/your/webroot;
        fastcgi_pass unix:/var/run/fcgiwrap.socket; # 部分系统路径为/run/fcgiwrap.socket,可根据实际调整
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
    
  3. 重启Nginx服务:
    systemctl restart nginx
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 15:47:18