Windows下Git Bash运行pytest报SyntaxError的解决方法求助
解决pytest运行时的语法错误问题
问题场景
编写了如下测试用例,保存为proj/tests/test_lesson1.py:
import pytest TOL = 2e-2 def squared(x): return x**2 def test_squared(): x = 4 expected = 16 computed = squared(x) msg = "fail" np.testing.assert_allclose(expected, computed, rtol=TOL, err_msg=msg)
在Windows的Git Bash终端执行以下命令:
alias py='C:/Users/name/anaconda3/envs/myenv/python.exe' . C:/Users/name/anaconda3/etc/profile.d/conda.sh conda activate myenv cd tests/ py -c "pytest test_lesson1.py"
得到错误:
File "<string>", line 1 pytest test_lesson1.py ^ SyntaxError: invalid syntax (myenv)
但执行py -c "print('hello world')"可以正常输出。
错误原因
py -c参数的作用是执行Python代码字符串,而pytest test_lesson1.py是命令行指令,并非合法的Python代码,因此触发语法错误。
正确运行方式
通过Python模块方式调用pytest
使用-m参数指定运行pytest模块,这是正确的调用方式:py -m pytest test_lesson1.py直接执行pytest命令(如果环境配置正确)
如果conda环境的Scripts目录已加入系统PATH,可直接运行:pytest test_lesson1.py
额外代码修正
测试用例中使用了np.testing.assert_allclose但未导入numpy,需在代码开头添加:
import numpy as np
内容的提问来源于stack exchange,提问作者a11
相关产品推荐
相关产品推荐

