如何正确安装 Python 依赖项? (也许没有须藤?)

How to install Python dependency properly? (maybe without sudo?)

我正在尝试 运行 使用 python 编写一些代码。它正在使用 tweepy 库。然后,我得到了这个错误:

Traceback (most recent call last):
  File "script.py", line 1, in <module>
    import tweepy
ImportError: No module named 'tweepy'

所以,我尝试安装依赖项: pip install tweepy 它被拒绝许可:

ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/sockshandler.py'
Consider using the `--user` option or check the permissions.

接下来要做的是 运行 使用 sudo。我对 docker 使用 sudo 的体验很糟糕,因为它会在我的本地创建受保护的文件。不过我还是试了一下sudo pip install tweepy 它 returns 成功了,但是当我尝试 运行 python3 myscript.py

时我仍然得到同样的错误

但是,我看到了一些升级 pip 的警告,所以我想也许就是这样。我尝试使用 pip install --upgrade pipsudo pip install --upgrade pip

升级 pip

还是不行..我尝试了最后一个技巧。改变终端。我想,"maybe after installing, some environment variable not running on this terminal"

没有。不工作。我承认这应该是一个新手问题。在网上尝试了一些解决方案,但仍然无法正常工作。谢谢。

查看报错信息:

... Permission denied: '/usr/local/lib/python2.7 ....

您在 python2 安装中安装了 tweepy。 请改用 pip3 install tweepy。当您再次收到权限被拒绝的错误时,可能会使用 sudo。之后你可以选择

python3 myscript.py

如果您使用 python3,您应该使用 pip3,pip 很可能是 python2 pip。

但是,更好的做法是使用 python3 -m pip install tweepy 以确保您将 pip 用于特定的 python 版本。

您也可以以用户身份安装它,而无需 sudo 仅用于您的本地帐户: python3 -m pip install --user tweepy

使用 --user 标志,像这样...

pip|pip3 install <PACKAGE> --user

这会将其安装在您的用户可用且可写的位置

https://packaging.python.org/tutorials/installing-packages/#installing-to-the-user-site

您的机器上似乎有 2 个 python 安装。 Python 3.x 和 Python 2.7。 当您 运行 pip 命令时,别名指向 pip2 ,它为 Python 2.7 安装软件包 - 这在您的错误消息

中很清楚
Permission denied: '/usr/local/lib/python2.7/dist-packages/sockshandler.py'

因此,如果您想为 python 3 安装软件包,请使用命令 pip3 而不是 pip

喜欢sudo pip3 install tweepy

如果您希望 pip 作为 pip3 工作,您可以考虑使用 alias pip=pip3

添加别名

您必须确保 pip 指向正确的 python 版本。