Python程序无法找到已安装的python3-cryptography包求助
问题解答
1. 查看python3-cryptography对应的Python版本
有两种直接验证方法:
- 分别用Python3.7和3.8的解释器检测:
如果3.7能输出类似# 检查Python3.7是否能识别cryptography python3.7 -c "import cryptography; print(cryptography.__file__)" # 检查Python3.8是否能识别cryptography python3.8 -c "import cryptography; print(cryptography.__file__)"/usr/lib/python3/dist-packages/cryptography/__init__.py的路径,3.8提示No module named 'cryptography',说明该包仅对应Python3.7。 - 查看apt包的依赖关系:
输出会显示依赖的Python版本(Raspbian buster的apt-cache show python3-cryptography | grep Dependspython3-cryptography依赖python3 (>= 3.7~),明确对应Python3.7)。
2. 报错是否是Rust的问题
是的。报错中的cargo rustc是Rust语言的构建工具,cryptography新版本的核心组件基于Rust开发,安装时需要编译Rust代码。出现code 101错误通常是以下原因:
- Raspbian buster默认的Rust/cargo版本过旧,不满足cryptography的编译要求;
- 缺少系统编译依赖(如
build-essential、libssl-dev、libffi-dev等); - 树莓派内存不足,编译Rust代码时内存耗尽导致失败。
3. 让Python3.8使用cryptography的解决方案
方案一:让Python3.8直接调用Python3.7的cryptography包
apt安装的python3-cryptography存放在/usr/lib/python3/dist-packages/目录下,可通过添加路径让Python3.8识别:
- 临时生效:运行程序前执行
之后用Python3.8启动程序即可。export PYTHONPATH=/usr/lib/python3/dist-packages:$PYTHONPATH - 永久生效:创建或编辑Python3.8的
sitecustomize.py文件,添加路径配置:
注意:此方法可能存在版本兼容性问题,若程序需要cryptography高版本API,可能出现功能报错。import sys sys.path.append('/usr/lib/python3/dist-packages')
方案二:解决pip3.8安装cryptography的编译问题
先安装必要依赖并更新Rust:
# 安装系统编译依赖 sudo apt-get install build-essential libssl-dev libffi-dev # 安装并更新Rust curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # 加载Rust环境变量 source $HOME/.cargo/env
若树莓派内存不足,临时扩容swap分区:
sudo fallocate -l 2G /swapfile sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile
然后重新安装:
pip3.8 install cryptography
安装完成后可关闭swap:
sudo swapoff /swapfile sudo rm /swapfile
方案三:使用预编译wheel包
直接下载对应Python3.8的arm架构预编译wheel文件(比如PyPI上的cryptography-*-cp38-cp38-linux_armv7l.whl),然后用pip安装:
pip3.8 install ./cryptography-xxx.whl
内容的提问来源于stack exchange,提问作者flyerbear
相关产品推荐
相关产品推荐

