python-3.x - 使用 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 可执行文件,那就是一个问题,因此您正在运行一个没有安装 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
推荐阅读
- cordova - 将 Cordova 与 React-Native 一起使用的可能性
- ruby-on-rails - Rails if 函数未提交 before_create
- performance - 找到游戏对象的更好(和更便宜)的方法?
- c# - ASP.net MVC 5 路由:加载基本 url 时出现 ajax 错误,但在最后添加 home/Index 时有效
- java - 我们可以在回收站视图中调整项目高度吗?
- ecmascript-6 - eslint --fix 在 ES6 字符串模板文字中引入了奇怪的空格
- r - 使用 ggplot 针对单个变量的因素(季度日期)绘制数字(价格指数)
- titanium - 如何在钛中为android的文本字段设置清除按钮?
- postgresql - 无法打开文件“pg_clog/0000”:没有这样的文件或目录
- java - 在 GraphView 中向 Y 轴添加左填充