Python导入torch包很好,但pytest没有;ModuleNotFoundError



我使用的是安装了PyTorch的conda。我有以下文件test.py:

import torch
def test_test():
print(torch.Tensor([1,2]))
test_test()

运行python test.py运行良好:

> python test.py
tensor([1., 2.])

但是用pytest运行它会给我一个错误:

> pytest test.py
(...)
ModuleNotFoundError: No module named 'torch'`.

这里怎么了?

pytest是全局安装的,而不是在coda环境中。安装conda install pytest解决了这个问题。

如果导入/使用使用torch的函数,但定义该函数的模块不导入torch,也可能发生这种情况。至少这就是我在确保pytest在环境中不起作用时解决问题的原因。

最新更新