安装包但不导入包

Package installed but doesn't import package

出于某种奇怪的原因,无论我安装哪个软件包,当我转到 import 时,它都不知道我在说什么软件包。我非常确定这是一个 Visual Studio 代码错误,但如果不是,我也在使用 Linux.

当我 pip installpyttsx3 这是我在终端中得到的:

Collecting pyttsx3
  Downloading https://files.pythonhosted.org/packages/24/4e/580726c73272344d3e74b7aaffae55ff6b6450061fbecb8cc6e112531c02/pyttsx3-2.7.tar.gz
Building wheels for collected packages: pyttsx3
  Running setup.py bdist_wheel for pyttsx3 ... done
  Stored in directory: /home/secretlloyd/.cache/pip/wheels/a2/8a/fe/11112aca9c89142c3a404bc67ef3393a7ad530da26639a05d4
Successfully built pyttsx3
Installing collected packages: pyttsx3
Successfully installed pyttsx3-2.7

但是当我 运行 一个例子时我得到这个错误:

Traceback (most recent call last):
  File "/home/secretlloyd/Visual Studio Code/Python/Finished/Text Colors/finished.py", line 1, in <module>
    import pyttsx3
ModuleNotFoundError: No module named 'pyttsx3'

3 种可能的情况:

  1. 当我没有注意到我同时使用两个 Pythons 一个 2.7 和另一个 3.6 时,同样的事情发生在我身上。确保知道您的软件包安装到您真正想要存储它的 Python 模块文件夹或另一个您不知道存在的文件夹中。

  2. 您的 PATH 可能配置不正确,如果您使用的是 Windows 或 Linux,请检查您的 PATH 变量是否配置正确。如果愿意,您可以重置配置。 (link=How to reload .bashrc settings without logging out and back in again?)

  3. 对于 Python 中的某些 packages/libraries,导入库的方式与您在 .py 文件中导入它的名称不同。例如:您可以通过 [pip install OpenCV] 安装 OpenCV 库,但是当将它导入到文件中时,您必须编写 [import cv2].

希望此信息对您的问题有所帮助。

您可以使用虚拟环境来安装您的库。如果这样做,每个项目都将拥有自己的范围库,而不会影响您的全局库。

如何使用虚拟环境?

输入项目的根文件夹,然后运行在bash上执行以下命令:

$ py -m venv .env
$ source .env/Scripts/activate

之后你会注意到你的 bash 会有一个像 (.env) 这样的前缀。然后你应该安装你的库:

(.env) $ pip install pyttsx3

为了停用虚拟环境只需运行以下命令:

(.env) $ deactivate

为虚拟环境设置 VS Code Intellisense

如果您使用 VSCode,您可以在设置虚拟环境后设置正确的 python 解释器。只需按照以下步骤操作:

  • 在您的项目中打开 VSCode
  • 按 F1
  • 类型:> python: select interpreter
  • 点击Enter path or find an existing interpreter
  • 点击Find
  • 导航到.env > Scripts > python