Vscode/pytest gives me an error when importing
-
I asked this question on the regular stackoverflow but i think you guys will be much more competent about this topic. My guess is that is some sort of python setup issue.
When I write an import line like this
from mypackage import something
and run it using vscode tools it gives my an error, when I run it using venv python it works. Same for pytest, I have to run it like this:python3 -m pytest tests
for it to work. The main thing that i'm trying to accomplish is to be able to run/debug stuff from vscode.The steps I took for it to work:
- Create venv & avtivate it
- Turned my project into a package
- Create setup.py
- pip3 install -e .
- Create a launch.json file
The launch.json file:
{ "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal", "args": ["-q", "data"] } ] }
And the setup file:
from setuptools import setup
setup(
name='mypackage',
version='0.1.0',
packages=['mypackage'],
scripts=['bin/script'],
license='LICENSE.txt',)
Expected behaviour:
- pytest not to give an import error
- vscode not to give an import error
What I get:
- works only when I explicitly run it like this:
python3 main.py
Trying to solve it for a solid hour. Many many many thanks for helping!
-
I'm guessing you created and activated in your terminal?
You need to tell vscode about the venv. It's pretty good at finding and using them but sometimes it dectects the wrong one.
At the bottom of the vscode window you should see the environment listed. If its the wrong one click it and find the right one.
Also your
launch.json
andsetup
file seems wrong.The
program
should probably bescript
orpython3 ${file}
inlaunch.json
.In your setup file
scripts
should bescripts=bin/my-cool-program
. Then you can changeprogram
inlaunch.json
tomy-cool-program
. You should also be able to run it from your terminal like$ my-cool-program -q data
.This is a great way to learn, but it's not how I would create a CLI program today in python. I think you would be better off using
poetry
andclick
. Here is an https://cjolowicz.github.io/posts/hypermodern-python-01-setup/ to "modern" python.