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

Python FileNotFoundError排查:文件存在但无法访问的CGI脚本问题

排查MacOS下CGI脚本FileNotFoundError的解决方案
  • 确认CGI服务器的工作目录
    脚本里的文件路径默认是相对服务器启动时的工作目录,而非脚本所在的cgi-bin目录。可以在脚本开头添加调试代码,打印当前工作目录来验证:

    import os
    print("Content-Type: text/plain\n")
    print("Current working directory:", os.getcwd())
    

    根据输出的目录,调整脚本内的文件引用路径。

  • 修正Shebang行指向正确的Python解释器
    由于用pyenv管理版本,系统默认Python可能不是你使用的3.11.3,推荐以下两种写法:

    1. 用env自动匹配当前环境的Python:#!/usr/bin/env python3
    2. 直接填写pyenv shims的绝对路径(可通过which python3命令查看):#!/Users/你的用户名/.pyenv/shims/python3
      注意Shebang必须是脚本第一行,开头不能有空格。
  • 检查文件及目录的完整权限
    除了给generate_list.py设置chmod +x,还要确保:

    • 脚本本身具备读权限:chmod 755 cgi-bin/generate_list.py
    • webapp和cgi-bin目录权限为755:chmod 755 webapp webapp/cgi-bin
      MacOS权限控制较严格,需保证服务器进程能正常读取这些文件和目录。
  • 确认CGI服务器的启动方式
    若使用Python自带的http.server,需用CGIHandler模式启动,且要在webapp目录下执行命令:

    python3 -m http.server --cgi 8000
    

    启动后直接访问http://localhost:8000/cgi-bin/generate_list.py测试。如果用Apache服务器,要确保httpd.conf中开启了CGI模块,并正确配置cgi-bin目录的权限规则。

  • 修正脚本内的文件路径引用
    脚本中如果有打开其他文件的代码(比如open("data.txt")),建议改为基于脚本自身目录的绝对路径:

    import os
    script_dir = os.path.dirname(os.path.abspath(__file__))
    target_file = os.path.join(script_dir, "data.txt")
    with open(target_file) as f:
        # 文件处理逻辑
    

内容的提问来源于stack exchange,提问作者Clu-Codes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 11:02:08