我在Ubuntu机器上运行Python 2.7.6。当我在终端中运行twill-sh
(Twill 是用于测试网站的浏览器)时,我得到以下结果:
Traceback (most recent call last):
File "dep.py", line 2, in <module>
import twill.commands
File "/usr/local/lib/python2.7/dist-packages/twill/__init__.py", line 52, in <module>
from shell import TwillCommandLoop
File "/usr/local/lib/python2.7/dist-packages/twill/shell.py", line 9, in <module>
from twill import commands, parse, __version__
File "/usr/local/lib/python2.7/dist-packages/twill/commands.py", line 75, in <module>
browser = TwillBrowser()
File "/usr/local/lib/python2.7/dist-packages/twill/browser.py", line 31, in __init__
from requests.packages.urllib3 import connectionpool as cpl
ImportError: No module named packages.urllib3
但是,我可以在 Python 控制台中导入 urllib 就好了。可能是什么原因?
如果您已经从默认版本安装了"请求",则可能必须
sudo pip install --upgrade requests
感谢@bkzland对先前答案的评论:
我按照这些步骤做了同样的错误,我需要使用 sudo pip 安装 --每次升级以使其正常工作。– bkzland 12 月 17 '15 在 12:57
---现在,我如何使它成为我 setup.py 中的依赖项?
标准urllib
和urllib2
与第三方urllib3
之间存在差异。
看起来斜纹没有安装依赖项,所以你必须自己做。斜纹取决于requests
库,该库在幕后附带并使用urllib3
。您还需要lxml
库和cssselect
库。
您可以按如下方式将它们安装在终端上:
pip install requests
pip install lxml
和
pip install cssselect
python3
#note that requests.packages.urllib3 is just an alias for urllib3
from urllib3 import disable_warnings
from urllib3.exceptions import InsecureRequestWarning
disable_warnings(InsecureRequestWarning)
如果您使用的是基于 RHEL 的口味,那么:
yum install -y python-requests
基于 Debian/Ubuntu 的风格:
apt-get install -y python-requests
基于 Arch Linux 的风格:
pacman -S python-requests
问题解决方式:
pip install --upgrade urllib3==1.19.1
pip install --upgrade requests
应该指出的是,如果你犯了我犯的菜鸟错误,使用"旧"python命令运行python 3脚本,即运行脚本
python3 <script>.py
不
python <script>.py
这里的问题是通过子依赖关系隐含地依赖于某些东西。这种风格等同于引用类的 dunder-方法,因为依赖项自己的依赖项可能会更改(例如,如果requests
停止使用/公开urllib3
)。
您可以通过明确使用依赖项来避免此问题,并将它们(即urllib3
)表示为requirements.txt
/pyproject.toml
文件中的依赖项。