如何解决pqcrypto库导入失败及安装构建问题?
Pylance无法解析pqcrypto导入,pip显示已安装但导入失败
环境信息
- VirtualBox中运行Ubuntu 22.04
- Python 3.10.6
- Pip 23.0.1
问题详情
尝试使用pqcrypto库时,Pylance提示:
Import "pqcrypto" could not be resolved Pylance (reportMissingImports)
最初执行pip install pqcrypto安装时,wheel构建失败,核心错误为cffi版本不匹配:
Exception: Version mismatch: this is the 'cffi' package version 1.15.1, located in '/tmp/pip-build-env-ifogc2y8/overlay/local/lib/python3.10/dist-packages/cffi/api.py'. When we import the top-level '_cffi_backend' extension module, we get version 1.15.0, located in '/usr/lib/python3/dist-packages/_cffi_backend.cpython-310-x86_64-linux-gnu.so'. The two versions should be equal; check your installation.
之后下载源码包执行sudo python setup.py install,安装完成后pip install pqcrypto显示已安装:
$ pip install pqcrypto Requirement already satisfied: pqcrypto in /home/mack/Desktop/RSAvsCK/venv/lib/python3.10/site-packages/pqcrypto-0.1.3-py3.10-linux-x86_64.egg (0.1.3) Requirement already satisfied: cffi<2.0.0,>=1.14.2 in ./.eggs/cffi-1.15.1-py3.10-linux-x86_64.egg (from pqcrypto) (1.15.1) Requirement already satisfied: pycparser in ./.eggs/pycparser-2.21-py3.10.egg (from cffi<2.0.0,>=1.14.2->pqcrypto) (2.21)
pip show pqcrypto也能正常读取库信息:
$ pip show pqcrypto Name: pqcrypto Version: 0.1.3 Summary: Post-quantum cryptography for Python. Home-page: https://github.com/kpdemetriou/pqcrypto Author: Phil Demetriou Author-email: inbox@philonas.net License: Location: /home/mack/Desktop/RSAvsCK/venv/lib/python3.10/site-packages/pqcrypto-0.1.3-py3.10-linux-x86_64.egg Requires: cffi Required-by:
已在虚拟环境内外尝试操作,但导入失败问题仍未解决。
解决方案
1. 修复cffi版本不匹配问题
wheel构建失败的根源是系统全局_cffi_backend版本与临时安装的cffi版本不一致,先统一版本:
# 卸载全局和虚拟环境中的cffi sudo pip3 uninstall -y cffi pip uninstall -y cffi # 安装与系统后端匹配的版本 sudo pip3 install cffi==1.15.0 # 激活虚拟环境后执行 pip install cffi==1.15.0
2. 重新正确安装pqcrypto
避免使用sudo python setup.py install(会导致权限和虚拟环境路径冲突),激活虚拟环境后重新安装:
# 激活虚拟环境 source /home/mack/Desktop/RSAvsCK/venv/bin/activate # 卸载已安装的pqcrypto pip uninstall -y pqcrypto # 重新用pip安装(此时cffi版本匹配,wheel可正常构建) pip install pqcrypto # 若仍失败,在虚拟环境内用源码安装(不要加sudo) cd pqcrypto源码目录 python setup.py install
3. 让Pylance识别虚拟环境
- 在VS Code中按
Ctrl+Shift+P,选择Python: Select Interpreter,选中虚拟环境路径/home/mack/Desktop/RSAvsCK/venv/bin/python - 等待Pylance重新索引,若仍报错则重启VS Code
- 检查
.vscode/settings.json,确保python.pythonPath指向虚拟环境的Python解释器
4. 验证导入可用性
直接运行Python脚本测试,排除Pylance索引问题:
import pqcrypto print(pqcrypto.__version__)
若运行无报错,说明是Pylance索引问题,按步骤3操作即可;若运行报错,检查虚拟环境是否激活、site-packages路径是否正确。
内容的提问来源于stack exchange,提问作者Mack Osborne
相关产品推荐
相关产品推荐

