I'm trying to import some local modules in Python while using VS Code as my editor. Something like this:
import folder1.subfolder2.program3
We'll say "folder1" is located at 'C:/folder1'
VS Code does not recognize this and I keep getting failed import statements. It instead thinks 'C:/folder6' (for example) is the path. How can I change the Python Path in VS Code?
I tried changing the PythonPath in Environment Variables and that didn't fix the problem. I know there is a launch.json file in VS Code I can create by debugging. Can I set the PythonPath there and how would I do it?
Edit: Some updates. I can manually add a PythonPath to a file like this:
os.environ['PYTHONPATH'] += os.pathsep + "C:\\folder1\\etc"
This is fine for running 1 file, but I often have dozens of interconnected files and don't want to add that line to every single one.
I also tried adding a launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"env": {
"PYTHONPATH": "C://folder1//etc"
}
}
]
}
That doesn't seem to be changing anything, though, when I run a.py file from the command line.
You need to tell the Python extension you want it to look for code outside of your current workspace. You can either add a "python.autoComplete.extraPaths"
setting or create a .env
file and set your PYTHONPATH
there.
I could be wrong here, but on vs code there is a python button on the bottom left that allows me to change the python path. The button says python3.8.1... I only code python, so you may have to have a.py file open or something like that.
VS Code only search on python path that is in status bar (PYTHON_PATH/lib/*) and directory of file that you are working not anywhere else (I couldn't find any setting to change this path). VS Code Statusbar
(So I recommend to put your package in PYTHON_PATH/lib)
Also this thing that you're saying (folder1.folder2/mypackage) is only possible if you put __init__.py
in each of directories
if you put your folder in directory of your file, tree of your working directory should be something like this:
cwd
|____ __init__.py
|____ folder1
|____ __init__.py
|____ subfolder2
|____ __init__.py
|____ program1.py
In this situation I think I would do this:
You can copy C:/folder1/folder2/mymodule.py
to your file_path, then try to import it with import mymodule
. See code below:
import rx7
rx7.files.copy('C:/folder1/folder2/mymodule.py', 'mymodule.py')
import mymodule
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.