在 CentOS 上运行 Python 报错的原因非常多,常见情况可以分为几类。下面我按最常见原因给你梳理一下,并给出对应的解决办法;如果你能贴出具体报错信息,我可以更精准地帮你定位。
CentOS 7/8 的 系统工具(yum、dnf)依赖自带的 Python(通常是 Python 2.7 或 3.6)。
/usr/bin/pythonpython 软链接改成了 Python 3bash: /usr/bin/python: No such file or directory
或
File "/usr/bin/yum", line 30
✅ 不要替换系统 Python
ls -l /usr/bin/python*
恢复软链接(示例):
ln -sf /usr/bin/python2.7 /usr/bin/python
-bash: python: command not found
或
-bash: python3: command not found
python 命令python3python3 --version
如需 python 命令:
sudo alternatives --set python /usr/bin/python3
或
alias python=python3
ModuleNotFoundError: No module named 'xxx'
确认 Python 和 pip 对应:
which python
which pip
安装模块:
pip3 install 包名
⚠️ 不建议直接用 pip 污染系统 Python,推荐用虚拟环境:
python3 -m venv venv
source venv/bin/activate
pip install xxx
pip is configured with locations that require TLS/SSL
或
SSL: CERTIFICATE_VERIFY_FAILED
yum install -y openssl-devel
或临时跳过(不推荐):
pip install xxx -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
PermissionError: [Errno 13] Permission denied
sudo pippip install --user xxx
| CentOS 版本 | 默认 Python |
|---|---|
| CentOS 7 | Python 2.7 |
| CentOS 8 | Python 3.6 |
| CentOS Stream | Python 3.9+ |
请贴出以下信息,我可以直接告诉你原因:
cat /etc/centos-release)python --version 或 python3 --version)如果你愿意,可以直接把报错贴出来,我帮你一行一行分析。