《笨办法学Python》虚拟环境配置后nosetests报错求助
问题背景
我按照《笨办法学Python》(Learn Python the Hard Way)的指引搭建Python虚拟环境,步骤如下:
- 安装virtualenv
- 创建
.venvs目录 - 依次创建
lpthw、projects及子目录skeleton - 为
skeleton目录添加结构:NAME、bin、setup.py、tests、docs - 激活虚拟环境并安装nose模块
- 运行nose测试
在PowerShell中进入skeleton目录,激活虚拟环境后执行nosetests时,出现以下属性错误:
if isinstance(tests, collections.Callable) and not is_suite:
AttributeError: module 'collections' has no attribute 'Callable'
尝试将相关文件中的collections.Callable改为collections.abc.Callable后,nose返回0个测试结果,但实际应至少有1个测试。我的setup.py代码如下:
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'description': 'My Project', 'author': 'William Smith', 'url': 'URL to go get it at.', 'download_url': 'Where to download it.', 'author_email': 'davwilsm1998@yahoo.com', 'version': '0.1', 'install_requires': ['nose'], 'packages': ['NAME'], 'scripts': [], 'name': 'projectname' } setup(**config)
已定位两个问题:
nosetests调用的是主Python安装目录的Lib文件夹,而非虚拟环境的Lib文件夹nosetests要么返回属性错误,要么未在正确目录运行测试
解决方案
一、修复当前虚拟环境的nosetests调用问题
确认虚拟环境已正确激活
激活虚拟环境后,PowerShell提示符前应显示虚拟环境名称(比如(lpthw))。若未激活,重新执行激活命令:# 假设虚拟环境目录为 .venvs/lpthw .\.venvs\lpthw\Scripts\Activate.ps1激活后执行
Get-Command nosetests,输出路径需指向虚拟环境的Scripts目录(如C:\Users\XXX\.venvs\lpthw\Scripts\nosetests.exe),而非系统Python目录。重新在虚拟环境中安装nose
先卸载全局或错误位置的nose,再在激活的虚拟环境中重新安装:# 卸载全局nose(若存在) pip uninstall nose -y # 激活虚拟环境后重新安装 pip install nose此举确保
nosetests脚本属于当前虚拟环境,避免调用系统版本。解决collections.Callable属性错误
该错误因Python 3.10+中collections.Callable被移至collections.abc.Callable,旧版nose不兼容。不建议直接修改系统文件,推荐安装兼容Python 3.10+的nose分支版本:pip install git+https://github.com/nose-devs/nose.git或者改用更现代且维护活跃的
pytest替代nose:pip install pytest # 运行测试 pytest
二、解决测试未被发现的问题
检查测试文件结构
nose默认识别tests目录下以test_开头的文件,且文件中的测试函数也需以test_开头。确保skeleton/tests目录下存在类似test_projectname.py的文件,示例内容:def test_basic(): assert 1 == 1配置测试路径
在skeleton目录下创建nose.cfg文件,指定测试目录:[nosetests] tests=tests或者修改
setup.py添加test_suite配置:config = { # 原有配置保留 'test_suite': 'tests', }之后执行
python setup.py test也可运行测试。
三、改用Python内置虚拟环境工具(替代virtualenv)
若virtualenv问题较多,推荐使用Python 3.3+内置的venv模块,步骤更简洁且无需额外安装:
- 创建虚拟环境:
python -m venv .\.venvs\lpthw - 激活虚拟环境:
.\.venvs\lpthw\Scripts\Activate.ps1 - 安装依赖:
pip install nose - 运行测试:
nosetests
内容的提问来源于stack exchange,提问作者Smitty_Code

