在 Ubuntu 上使用 Python 出错时,可以按下面思路一步步排查和解决:
不同错误处理方式完全不同:
命令找不到(command not found)
python: command not found
python3python3 --version
或用:sudo apt install python3
Permission denied
PermissionError: [Errno 13] Permission denied
sudo 乱跑脚本chmod +x script.py
ModuleNotFoundError
ModuleNotFoundError: No module named 'xxx'
pip3 install xxx
sudo apt install python3-pip
版本冲突
python3 -m venv venv
source venv/bin/activate
pip3 install xxx -i https://pypi.tuna.tsinghua.edu.cn/simple
sudo apt install ca-certificates
sudo apt install python3-dev build-essential
查看:
which python3
ls /usr/bin/python*
建议用 update-alternatives 或虚拟环境,不要删系统 Python。
python3 your_script.py
import traceback
traceback.print_exc()
请把以下发我:
lsb_release -a)我可以直接帮你定位并给解决命令。