已安装程序包,但未导入程序包

2024-10-02 02:34:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

当我pip install打开包pyttsx3时,这就是我在终端中得到的:

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'

Tags: pipinpyimporthomeforpackages错误
2条回答

您可以使用虚拟环境来安装libs。如果这样做,每个项目将有自己的作用域lib,而不会影响全局lib

如何使用虚拟环境?

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

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

之后,您会注意到bash将有一个类似于(.env)的前缀。然后,您应该安装LIB:

(.env) $ pip install pyttsx3

要停用虚拟环境,只需运行以下命令:

(.env) $ deactivate

虚拟环境的设置与代码智能感知

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

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

3种可能的情况:

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

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

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

我希望这些信息对您的问题有所帮助

相关问题 更多 >

    热门问题