Chandan Nayak
Chandan Nayak

Reputation: 10927

vscode import error for python module

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

Upvotes: 64

Views: 193329

Answers (12)

windyvation
windyvation

Reputation: 561

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.

Upvotes: 0

Anna Madsen
Anna Madsen

Reputation: 492

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

Upvotes: 2

user3814004
user3814004

Reputation: 159

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

Upvotes: 1

Mubashar Javed
Mubashar Javed

Reputation: 1367

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!

Upvotes: 16

W.Perrin
W.Perrin

Reputation: 4725

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.

Upvotes: 4

Alfa Bravo
Alfa Bravo

Reputation: 1991

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

Upvotes: 1

Dylan Wang
Dylan Wang

Reputation: 131

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

Upvotes: 9

Paulus
Paulus

Reputation: 1457

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"

Upvotes: 5

G4th
G4th

Reputation: 221

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

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

Upvotes: 19

LongToeBoy
LongToeBoy

Reputation: 195

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

Upvotes: 2

dcarl661
dcarl661

Reputation: 322

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

Upvotes: 10

ChenHao Wu
ChenHao Wu

Reputation: 869

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

Upvotes: 76

Related Questions