66

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}"
 }
10
  • 2
    "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. Commented Oct 2, 2017 at 7:38
  • 2
    Possible duplicate of How to properly determine current script directory in Python? Commented Oct 2, 2017 at 7: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. Commented Oct 2, 2017 at 8:02
  • Where does the build task set the CWD (Current Working Directory) to be? Commented Oct 2, 2017 at 19:58
  • 1
    This is a known issue with VSCode and setting the cwd and similar does NOT work. Commented Dec 4, 2018 at 13:56

12 Answers 12

76

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

Sign up to request clarification or add additional context in comments.

6 Comments

I also needed to restart VS Code afterwards.
Where can I find launch.json?
@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.
launch.json is no longer found in latest vscode.
@JohnJiang If there's no .vscode directory you can just make one (in the project directory). Then you can create launch.json in there.
|
20

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

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

3 Comments

where is launch.json located?
That did it for me too, thanks. It started failing out of the blue after the weekend. I guess a VS update
Would it be safe to put this directly in settings.json?
16

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!

1 Comment

If your hurt is like mine - What is python.jedi doing? See this
10

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

1 Comment

For me this was the correct answer.
9

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",

Comments

5

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"

1 Comment

Out of interest, why the downvote? I tried to answer correctly and point out things that could cause the problem?
4

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.

Comments

3

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

Comments

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

1 Comment

this one did it for me, thanx
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

Comments

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!.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.