vscode import error for python module
Asked Answered
H

12

60

I am trying to do an import in python from one directory level up.

import sys

sys.path.append('..')
from cn_modules import exception

I get an Error from VSCode when I try to do Run Build Task as:

ImportError: No module named cn_modules

The same code works without any error from terminal (python).
I face the problem when I try to run it from VSCode Run Build task.
Any clue on what is wrong here?

Have spent quiet some time but not able to resolve this, Any help is appreciated.


NOTE: this works when i do debug using vscode too. Below are my config for launch.json and tasks.json

launch.json

 {
        "version": "0.2.0",
        "configurations": [
            {
                "name": "Python Console App",
                "type": "python",
                "request": "launch",
                "stopOnEntry": true,
                "program": "${file}",
                "externalConsole": true,
                "debugOptions": [
                    "WaitOnAbnormalExit",
                    "WaitOnNormalExit"
                ],
                "env": {},
                "envFile": "${workspaceRoot}/.env",
                "console":"integratedTerminal",
                "pythonPath": "${config:python.pythonPath}"
            }
        ]
    }

tasks.json

{
        "version": "0.1.0",
        "command": "/usr/bin/python",
        "isShellCommand": true,
        "args": ["${file}"],
        "showOutput": "always",
        "env": {},
        "envFile": "${workspaceRoot}/.env",
        "pythonPath": "${config:python.pythonPath}"
 }
Henna answered 2/10, 2017 at 5:50 Comment(10)
"one directory level up"... from where? Are you aware of the current working directory? If you want to go up a directory from the location of your script, then you need to find the path of your script first.Handset
Possible duplicate of How to properly determine current script directory in Python?Handset
I do not have any problem running the code in python, it works. I am facing the problem when trying to run the same from vscode build task.Henna
Where does the build task set the CWD (Current Working Directory) to be?Stigmatism
In my case, re-open project folder cleared import errors. github.com/Microsoft/vscode/issues/10391Semiconscious
This is a known issue with VSCode and setting the cwd and similar does NOT work.Idler
@ChandanNayak did you find a solution to this issue? Experiencing similar behaviour. import works via the terminal but not within vscode.Hardnosed
@Hardnosed Nope, i did not and I started using pycharm. So have not looked back into it.Henna
@ChandanNayak, thanks for the reply, may have to do the sameHardnosed
All I did was replace my entire launch.json and that got it working. Thank you!!Toner
P
72

I tried to add this in my launch.json, then it works!

"env": {"PYTHONPATH": "${workspaceRoot}"}

below is my launch.json

        "name": "Python: Current File (Integrated Terminal)",
        "type": "python",
        "request": "launch",
        "program": "${file}",
        "cwd": "${workspaceRoot}",
        "env": {"PYTHONPATH": "${workspaceRoot}"},
        "console": "integratedTerminal"

wish it can help u! :)

Plumbago answered 5/12, 2018 at 2:8 Comment(6)
I also needed to restart VS Code afterwards.Formication
Where can I find launch.json?Antimacassar
@JamesHuang press ctrl + shift + p and type launch.json and then hit enter.Zelaya
@JamesHuang Configurations are defined in a launch.json file that's stored in a .vscode folder in your workspace. If it doesn't exist, it can be initialized via the debug menu from the sidebar.Creepie
launch.json is no longer found in latest vscode.Chazan
@JohnJiang If there's no .vscode directory you can just make one (in the project directory). Then you can create launch.json in there.Fernandina
C
16

In your launch.json file, change env:{} to:

"env": {"PYTHONPATH": "${workspaceRoot}"}
Commentate answered 3/4, 2018 at 13:58 Comment(3)
where is launch.json located?Displume
That did it for me too, thanks. It started failing out of the blue after the weekend. I guess a VS updateTrample
Would it be safe to put this directly in settings.json?Sandasandakan
M
15

The solution is given below just worked for me.

  1. Press Ctrl+Shift+P
  2. Type: Configure Language Specific Setting
  3. Then select Python
  4. settings.json will open. Check in this JSON file if there is a line like this:
{"python.jediEnabled": false}

(Press Ctrl+F and then paste the above line to find it quickly)

  1. If yes, then delete or comment this line, save the file and reload VScode.
  2. DONE!
Myo answered 28/9, 2019 at 13:58 Comment(1)
If your hurt is like mine - What is python.jedi doing? See thisErebus
D
8

In my case, it's nothing to do with

"env": {"PYTHONPATH": "${workspaceRoot}"}

Here is my folder/module structure:

/Dev/csproj/deploy/test.py 
/Dev/csproj/util/utils.py

and in test.py, it imports the utils function

import sys
sys.path.append('../')
from util.utils import get_keyvault_secret

It has no issue if I run test.py in terminal folder /Dev/csproj/deploy/.
But if I want to debug test.py in VSCode (under workspaceRoot), I got the exception of "ModuleNotFoundError"
To fix it, I add this to my debug configuration launch.json

"cwd": "${workspaceRoot}\\Dev\\csproj\\deploy",
Dispenser answered 18/3, 2019 at 23:0 Comment(0)
S
8

Thanks Honza Kalfus jankalfus

I have noticed that if I use File -> Close folder and then File -> Open Folder... and open the project folder again, the errors are gone. If I just restart VS Code instead, I keep getting the errors. I presume that some internal cache gets cleared?

Found here https://github.com/Microsoft/vscode/issues/10391

Streamy answered 3/4, 2019 at 20:34 Comment(1)
For me this was the correct answer.Daukas
C
4

I have had the same problem, in my case it was caused by the current directory of the vscode debug process being different to the directory the script was in. It is helpful to do a

print('cwd is %s' %(os.getcwd()))

Just before your sys.path.append and your imports. What happened with me is that the running environment cwd seems to default to the workspace directory, which seems to be the directory containing the vs code project file, and if this is not where your script is located, then your relative include paths are broken.

A solution to this is to insure that your script changes its current directory to the directory where the script is located, and also to append your syspath to the directory where the script is located:

scriptdir = os.path.dirname(os.path.realpath(__file__))
print('dir containing script is %s' % (scriptdir))

# append our extra module directory (in this case Autogen) onto the script directory

sys.path.append(os.path.join(scriptdir, 'Autogen'))

# also change cwd to where the script is located (helps for finding relative files)
print('============\ncwd is %s' %(os.getcwd()))

os.chdir(scriptdir)
print('============\ncwd after change to script dir is %s' %(os.getcwd()))

All the above steps will help to make your script run well, but they will not help for intellisense or code completion. To have the code completion run well, you must create a .env file (usually in the same directory as your .vscode directory) and in your .env file you add the directories where you want vscode to look for extra python modules

Contents of .env file

PYTHONPATH="someDirRelativeTowhereYourVSCodeProjectLives\\Autogen"
Contrarious answered 14/4, 2020 at 9:29 Comment(1)
Out of interest, why the downvote? I tried to answer correctly and point out things that could cause the problem?Contrarious
M
3

There are two ways. Directly put it in launch.json or use a .env file.

All in launch.json

launch.json

"env": {"PYTHONPATH": "${workspaceRoot};${workspaceRoot}/modules;${workspaceRoot}/modules/somePrj/modules"}

Use a .env file

launch.json

"envFile": "${workspaceRoot}/.env"

.env

PYTHONPATH=".;modules;/modules/somePrj/modules"

The .env file way is recommended for we can choose prod.env or test.env.

Marauding answered 16/8, 2020 at 4:53 Comment(0)
C
2

i did nothing but to add header in the beginning

#!/usr/bin/env python

that fixed my problem... maybe it will help somebody who is new just like me

Contrail answered 12/4, 2020 at 1:5 Comment(0)
S
2

For me, the issue had to do with a mismatch in the selected Python interpreter in VSCode, versus the overall used version of Python on my computer.

The selected Python interpreter in VSCode was Pyhon 3.8.10 64-bit (microsoft store) (which was the recommended version):

enter image description here

Whereas the current global version of Python on my laptop was Python 3.10.4

enter image description here

After changing the interpreter to Python 3.10.4 64-bit, all the import errors disappeared

Spikes answered 2/9, 2022 at 13:31 Comment(0)
M
1

Since this is a VScode question I could add what my answer was.

We are running many Python Django backends in a backends folder like so:

+projectBackends
    -oneService
    -twoService
    -threeService

And so in my project folder in VScode I just opened the projectBackends folder, because this would then give me all the services underneath it all at once. Seemed clear and simple. But then all the linting gets done from the root folder which is projectBackends, and not from the root folder of each service:

from oneService.module1 import view

gave and import error, where if I put

from projectBackends.oneService.module1 import view

I got no error, but then the microservice would not work.

So in the end I just added a folder for every microservice in my workspace like:

+oneService
+twoService
+threeService

Which solved all the import errors for the independant microservices

Manikin answered 6/8, 2020 at 7:51 Comment(0)
A
1

Until MSFT figures out how to really resolve this issue create a symlink between the file you are wanting to import to the folder where the Python environment you are using is installed and that resolved the problem for me.

Adding path to Win10 did not work xtraPath.json change did not work (how to specifically fill in what goes between the paren is a mystery)

Wasted three days on this. Hope the VSCode people read this. You are wasting thousands of hours not fixing this problem EASILY. It takes infinitely more time to set up your IDE than to get some project working. Stop wasting people's time!.

Airtight answered 5/6, 2022 at 22:13 Comment(0)
S
0

Similar to @anna madsen, I changed my python interpreter.

Then, when I tried to run a python file that imported a .py file from a different folder, that didn’t work when I tried via the vscode terminal.

However, when I opened the .py file and ran it from the menu Run > Run Without Debugging, then this worked.

And now, when I run the file from the vscode terminal, that works too. There may have been some initialization by running the file from the run menu that fixed whatever my setup gap was.

Sponsor answered 22/12, 2023 at 22:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.