vscode import error for python module

Python 2.7Visual Studio-CodeVscode SettingsVscode Tasks

Python 2.7 Problem Overview


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

Python 2.7 Solutions


Solution 1 - Python 2.7

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

Solution 2 - Python 2.7

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!

Solution 3 - Python 2.7

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

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

Solution 4 - Python 2.7

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

Solution 5 - Python 2.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

Solution 6 - Python 2.7

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"

Solution 7 - Python 2.7

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

Solution 8 - Python 2.7

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.

Solution 9 - Python 2.7

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChandan NayakView Question on Stackoverflow
Solution 1 - Python 2.7ChenHao WuView Answer on Stackoverflow
Solution 2 - Python 2.7Mubashar javedView Answer on Stackoverflow
Solution 3 - Python 2.7G4thView Answer on Stackoverflow
Solution 4 - Python 2.7Dylan WangView Answer on Stackoverflow
Solution 5 - Python 2.7dcarl661View Answer on Stackoverflow
Solution 6 - Python 2.7PaulusView Answer on Stackoverflow
Solution 7 - Python 2.7LongToeBoyView Answer on Stackoverflow
Solution 8 - Python 2.7W.PerrinView Answer on Stackoverflow
Solution 9 - Python 2.7Alfa BravoView Answer on Stackoverflow