首页 > 解决方案 > 使用 CGI - python 在查找模块时遇到问题

问题描述

我正在尝试通过 CGI 运行 python 脚本,但出现内部服务器错误

根据apache2的错误日志:

[Mon Dec 21 10:43:19.073771 2020] [cgi:error] [pid 7531] [client ::1:50038] AH01215:   File  "/usr/lib/cgi-bin/pytest.py", line 5, in <module>: /usr/lib/cgi-bin/pytest.py
[Mon Dec 21 10:43:19.073809 2020] [cgi:error] [pid 7531] [client ::1:50038] AH01215:     from  bs4 import BeautifulSoup                                       : /usr/lib/cgi-bin/pytest.py
[Mon Dec 21 10:43:19.073832 2020] [cgi:error] [pid 7531] [client ::1:50038] AH01215:  ModuleNotFoundError: No module named 'bs4': /usr/lib/cgi-bin/pytest.py

这都是关于我想通过 CGI 运行的一个非常简单的爬虫脚本。我要强调的是,通过终端正常运行这个脚本是没有问题的,它只是使用 CGI 的问题

是否有可能解决这个问题,或者 CGI 不适合这类脚本?

代码:

#! /usr/bin/python3

# enable debugging
import cgitb
from bs4 import BeautifulSoup                                       
from urllib.request import urlopen, Request
import os

cgitb.enable()

print ("Content-type: text/html\r\n\r\n")

print("hello")


url = "https://www.xxxxxxxxxxxxx"

soup = BeautifulSoup(urlopen(url).read())

...

标签: python-3.xcgi

解决方案


如果它不是同一个 Python 可执行文件,那就是一个问题,因此您正在运行一个没有安装 BeautifulSoup 的 Python 安装。您需要使用相同的可执行文件或从可执行文件创建虚拟环境,在虚拟环境中安装所需的模块并将 shebang 指向虚拟环境中的 Python 可执行文件。

例如,要将/usr/bin/python3可执行文件与具有您的模块的虚拟环境一起使用:

cd /home/usr/mydir
/usr/bin/python3 -m venv my_venv
cd my_venv/bin
. activate
pip install bs4
deactivate

然后将shebang改为指向:

#!/home/usr/mydir/my_venv/bin/python3

推荐阅读