为 python VS Code 导入 mysql.connector 时出现 ModuleNotFoundError [英] ModuleNotFoundError when importing mysql.connector in for python VS Code

查看:243
本文介绍了为 python VS Code 导入 mysql.connector 时出现 ModuleNotFoundError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经下载了 mysql.connector 和 mysql 但仍然存在同样的问题

I have downloaded mysql.connector and mysql but still there is the same issue

import mysql.connector
mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="Password"
)

print(mydb)

ModuleNotFoundError: 没有名为 'mysql' 的模块 - 这是错误

ModuleNotFoundError: No module named 'mysql' - this is the error

推荐答案

对此有两种可能的解决方案,但首先是一条建议:永远不要直接运行命令 pip.你真正想要的是 -m pip,将 替换为您要为其安装的特定 Python 的路径.这样您就可以保证 pip 将安装到您期望的环境/解释器中,而不仅仅是 pip 恰好在您的 PATH 上的第一个.

There's two potential solutions to this, but first a piece of advice: never run the command pip directly. What you really want is <path to python> -m pip, replacing <path to python> with the path to the specific Python you want to install for. That way you guarantee that pip will install into the environment/interpreter you expect instead of just whatever pip happens to be first on your PATH.

除此之外,选项一是确保您在 Python 扩展中选择的 Python 环境与您安装的环境相匹配.简单地运行 pip 并不能保证这一点,因此很可能您已经安装到一个版本的 Python 中,但将 Python 扩展连接到另一个版本.您可以运行Python:选择解释器 以选择适当的环境(或单击状态栏中的 Python 解释器详细信息).

With that out of the way, option one is to make sure that the Python environment you have selected in the Python extension matches the one you have been installing into. Simply running pip does not guarantee this, and so it's quite possible you have been installing into one version of Python but connecting the Python extension to another. You can run Python: Select interpreter in the command palette to choose the proper environment (or click on the Python interpreter details down in the status bar).

第二种选择——在我看来是更好的选择——是创建一个虚拟环境并在那里进行安装.所以你可以做 -m venv .venv 在您工作区的目录中,Python 扩展会选择它并询问您是否要使用该虚拟环境.当你打开一个新终端时,它应该激活那个虚拟环境,让你运行 python -m pip 来安装到那个虚拟环境中(你也可以手动激活或者简单地指定 Python 解释器的路径运行-m pip时直接在虚拟环境中).

The second option -- and in my opinion the better one -- is to create a virtual environment and do the installation in there. So you could do <path to python> -m venv .venv in the directory of your workspace and the Python extension will pick this up and ask if you want to use that virtual environment. When you open a new terminal it should activate that virtual environment, letting you run python -m pip to install into that virtual environment (you can also do the activation manually or simply specify the path to the Python interpreter in the virtual environment directly when running -m pip).

这篇关于为 python VS Code 导入 mysql.connector 时出现 ModuleNotFoundError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆