I've got a project with a suite of Python unit tests (using the unittest framework) that import Pytorch and cv2. I am able to run them all from the command line with
python -m unittest discover -s tests/
But get import errors in the VSCode UI when I try to load them:
Failed to import test module: test_overlays
Traceback (most recent call last):
File "XXX\AppData\Local\Continuum\anaconda3\lib\unittest\loader.py", line 436, in _find_test_path
module = self._get_module_from_name(name)
File "XXX\AppData\Local\Continuum\anaconda3\lib\unittest\loader.py", line 377, in _get_module_from_name
__import__(name)
File "XXX\tests\test_overlays.py", line 13, in <module>
...
import torch
ModuleNotFoundError: No module named 'torch'
My project is structured as a "wrapper application" importing utilities from a core library:
main_proj/
library/
packages and modules importing torch
tests/
unit tests for the application
The tests generally test only the wrapper application (there are separate tests for the library), but I occasionally import modules from library/
.
Because the tests are outside main_proj/library
, I need to add the library explicitly to the path at the top of each unit test:
import unittest
import sys
import os, os.path
sys.path.append(os.path.join(os.getcwd(), 'library'))
Why does this arrangement work just fine from the command line, but not from VSCode?
What resolved this issue was to:
Update VSCode to the latest version
Switch to an older Python 3.6 Anaconda environment (Ctrl+Shift+P, then Choose Interpreter...) -- I'm not sure this step is necessary
Close VSCode
Delete the Python extensions and reinstall them:
From git bash:
cd ~/.vscode/extensions
rm -fr *python*
Re-open VSCode and navigate to the extensions panel (Cog wheel->Extensions) and search for Python)
Afterward, I was able to use my Python 3.8+Torch 1.12 environment without any hitches.
It seems that something between VSCode and the Python extensions can occasionally get corrupted and requires a clean start in order to recover.