59

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}"
 }
Chandan Nayak
  • 10,117
  • 5
  • 26
  • 36
  • 2
    "one directory level up"... from _where_? Are you aware of [the current working directory](https://en.wikipedia.org/wiki/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. – Aran-Fey Oct 02 '17 at 07:38
  • 2
    Possible duplicate of [How to properly determine current script directory in Python?](https://stackoverflow.com/questions/3718657/how-to-properly-determine-current-script-directory-in-python) – Aran-Fey Oct 02 '17 at 07:40
  • 3
    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. – Chandan Nayak Oct 02 '17 at 08:02
  • Where does the build task set the CWD (Current Working Directory) to be? – ifconfig Oct 02 '17 at 19:58
  • In my case, re-open project folder cleared import errors. https://github.com/Microsoft/vscode/issues/10391 – jef Nov 14 '17 at 17:21
  • 1
    This is a known issue with VSCode and setting the `cwd` and similar does NOT work. – gented Dec 04 '18 at 13:56
  • @ChandanNayak did you find a solution to this issue? Experiencing similar behaviour. `import` works via the terminal but not within vscode. – Josmoor98 Dec 06 '19 at 12:37
  • @Josmoor98 Nope, i did not and I started using pycharm. So have not looked back into it. – Chandan Nayak Dec 06 '19 at 12:47
  • @ChandanNayak, thanks for the reply, may have to do the same – Josmoor98 Dec 06 '19 at 12:51
  • All I did was replace my entire launch.json and that got it working. Thank you!! – Kyle Feb 25 '22 at 19:52

11 Answers11

71

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! :)

ChenHao Wu
  • 819
  • 6
  • 6
  • 2
    I also needed to restart VS Code afterwards. – karu Aug 07 '20 at 15:12
  • 9
    Where can I find launch.json? – James Huang Nov 24 '20 at 19:03
  • @JamesHuang press ctrl + shift + p and type launch.json and then hit enter. – Yuvraj Singh Jadon Feb 04 '21 at 11:38
  • 2
    @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](https://code.visualstudio.com/docs/python/debugging#_initialize-configurations). – bwdm Mar 08 '21 at 17:41
  • 5
    launch.json is no longer found in latest vscode. – John Jiang Apr 01 '21 at 17:31
  • 3
    @JohnJiang If there's no .vscode directory you can just make one (in the project directory). Then you can create launch.json in there. – Raid Jun 29 '21 at 17:34
15

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

"env": {"PYTHONPATH": "${workspaceRoot}"}
Daniel
  • 8,655
  • 5
  • 60
  • 87
G4th
  • 181
  • 1
  • 3
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!
Mubashar Javed
  • 1,197
  • 1
  • 9
  • 17
  • 6
    If your hurt is like mine - What is `python.jedi` doing? See [this](https://stackoverflow.com/questions/55897160/what-is-the-difference-between-jedi-and-python-language-server-in-vs-code-ide) – Timo Jul 02 '21 at 19:32
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",
Dylan Wang
  • 111
  • 1
  • 5
7

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

dcarl661
  • 177
  • 3
  • 9
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"
Paulus
  • 1,385
  • 16
  • 20
  • Out of interest, why the downvote? I tried to answer correctly and point out things that could cause the problem? – Paulus Apr 21 '20 at 08:14
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.

W.Perrin
  • 4,217
  • 32
  • 31
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

LongToeBoy
  • 195
  • 10
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

Alfa Bravo
  • 1,961
  • 2
  • 25
  • 45
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!.

Ethan
  • 881
  • 8
  • 14
  • 26
user3814004
  • 139
  • 1
  • 10
1

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

Anna Madsen
  • 384
  • 3
  • 15