sssbbbaaa
sssbbbaaa

Reputation: 244

Set cwd in VS CODE

VS CODE 1.52.1 Python 3.7.9

Path structure


In the past, I could import "MainModule.py" in all of sub-modules in any directory easily like below.

import MainModule

But after I reinstall VS Code, they are unable to find modules in different paths. I've found some solutions importing modules with absolute paths, but there are hundreds sub-modules already making hard to modify them all.

I tried below but nothing works.

  1. Modifying cwd

In "SubModule_a.py",

import os
os.chdir("C:\\work\\Folder Main")
import MainModule

This still arises ModuleNotFoundError

  1. Modifying "MyWorkspace.code-workspace"

    "settings": {

     "python.pythonPath": "C:\\anaconda3\\envs\\MyEnv\\python.exe", # for virtual env
     "python.linting.pylintEnabled": true,
     "python.linting.enabled": true,
     "terminal.integrated.cwd": "C:\\work\\Folder Main" # added this line
    

    }

In short, how can I import "MainModule.py" from "SubModule_A.py" without using absolute path?

Upvotes: 3

Views: 3037

Answers (1)

Molly Wang-MSFT
Molly Wang-MSFT

Reputation: 9481

To import the module successfully, there're two optional ways:

1.Add the following code in launch.json:

"env": {
    "PYTHONPATH":"${workspaceFolder}"
},
"cwd": "${workspaceFolder}"

Then run it through Run without Debugging(Ctrl+F5). It will still throw error if you run by clicking the green triangle button in the upper right corner.

enter image description here

2.Append the current path:

import sys
sys.path.append('./')
from FolderMain import MainModule

When we import a module, python interpreter will search in the current directory, installed built_in modules and third-party modules, the search path is stored in sys.path. ./ represents the current path.

enter image description here

This works both, whatever you run it without debugging or in Terminal.

Upvotes: 4

Related Questions