Default Python paths when using VSCode interactive window - python

Suppose the Python package mypackage is at a non-standard location on my machine and I am running Python code in the VSCode interactive window. If I type
import mypackage
it will not be found. This can be remedied by doing sys.path.append("/path/to/mypackage"). However, I would like to set things up so that within a given project each time I open the interactive window a set of paths, like /path/to/mypackage, have already been added to the search path. Is there a way to do this?

You can do this to modify the PYTHONPATH:
Add these in the settings.json file to Modify the PYTHONPATH in the terminal:
"terminal.integrated.env.windows": {
"PYTHONPATH": "xxx/site-packages"
}
Create a .env file under your workspace, and add these settings in it to modify the PYTHONPATH for the extension and debugger:
PYTHONPATH=xxx/site-packages
You can refer to [here][1] to understand the effects of these two configurations.

Related

How to set PYTHONPATH for all tools in Vscode (on Windows)?

I have a folder mysrc in my project root and I'd like to make all tools of VScode work with import mysrc. The only way I found to make it work is to put the full absolute path PYTHONPATH=<fullpath_to_workfolder> in the .env file. But ideally I'd like to use relative paths to the workfolder.
How can I do that?
All suggestions I found (also here) somehow do not work. ${workspaceFolder} is empty. PYTHONPATH=. does not work. Ideally I'd configure a single PYTHONPATH and not for every tool (terminal, notebooks, mypy, ...). And even my solution for whatever reason duplicates PYTHONPATH=<fullpath_to_workfolder>;<fullpath_to_workfolder> on Windows when I inspect this variable in my code. I believe on Linux I did not have issues.
I'm not sure if this is what you want, but you could create a batch file with the following lines:
#echo off
set PYTHONPATH=%cd%
"%LOCALAPPDATA%\Programs\Microsoft VS Code\Code.exe"
(assuming default VS Code installation directory — you might have to change the last line if you installed it in another directory.)
This would call VS Code with the PYTHONPATH environment variable set to the directory from where you call it.
You can confirm this by opening a terminal window in VS Code and typing echo %PYTHONPATH%. All processes spawned from VS Code will inherit the environment variables, so this should work for all tools.
If you copy the batch script to another project and call it from there, all tools would then use that directory.
Sorry, but it works when I add these in the .env file:
PYTHONPATH=.\
or
PYTHONPATH=.
Could you reconfirm it?
Update:
.env file has no influence on the Jupyter NoteBook, but it works on linters, formatters, IntelliSense, and testing tools.
You can configure this to achieve it:
"jupyter.notebookFileRoot": "${workspaceFolder}",

Adding to PYTHONPATH in VS Code

I'm trying to add the src folder to my PYTHONPATH i.E. do the same thing as Mark directory as sources root in PyCharm.
I've looked at the solutions to Visual Studio Code - How to add multiple paths to python path? but the solutions shown there do not work for me.
I've set up my minimal example as follows shown in the screenshot below:
My understanding would be that having a .env file with PYTHONPATH="./src;${PYTHONPATH}" would add the src file to the path.
Nevertheless, when running the code runner or when running python change_pyhton_path.py src is not part of the PYTHONPATH and the direct import from src fails.
I do have setting "python.envFile": "${workspaceFolder}/.env".
In pyCharm on the other hand everything works as it should after hitting Mark directory as source on src.
Thanks for helping out!
in your settings.json add:
"terminal.integrated.env.windows": {
"PYTHONPATH": "full python path here"
}
if you have problems with importing modules and you are using code-runner, try to add
"code-runner.fileDirectoryAsCwd": true
to your settings.json file
If you are trying to get auto complete working from your source directory, you could add to the PYTHONPATH environment variable as you are doing. You can also go the "vscode native" route, as there is a configuration. Open your workspace settings and add the following line:
"python.autoComplete.extraPaths": ["./src"]
NOTE: Avoid setting this at the user level as each project differs in where the source code lives
I dont know much but the json PYTHONPATH setting above looks like it would work as the json.settings file is definatly going to nead to know about your interpreter. Once you have a Python terminal prompt you have to run pythons pip file to integrate all the neccesary libraries . VS Code itself tells you to go to the command pallete and install either a venv virtual environment or create a conda (from anaconda or miniconda) set up for it. I am trying to do it myself so once I crack it I'll have more info.

Adding Python package to path for VSCode terminal

I'm writing python classes in a package using VScode. I want to add this package's parent directory to the Python path when using the VScode Terminal so I can import the package (regardless of the directory of the file that's being run).
I've tried a .env file and Workspace settings without success.
Ultimately I want to run doctests on the classes using the terminal, and for that the terminal needs to be able import the package.
.env File
I have a Workspace. I first tried adding a .env file as follows (note I'm using Python 3 Anaconda on Windows):
PYTHONPATH=C:\\MyPython;${PYTHONPATH}
(I've tried single & double back slashes and forward slashes, nothing works).
When I run a script (test.py) in the terminal containing this:
print(os.environ.get('PYTHONPATH'))
I just get back None.
I did try setting a system wide PYTHONPATH environment variable in Windows, which then shows up, but the C:\MyPython is not added to it. I don't want to have to add/change the system PYTHONPATH every time I open a different Workspace!
Workspace Settings
I then tried adding Workspace settings in the MyProject.code-workspace file:
{
"folders": [
{
"path": "C:\\MyPython"
}
],
"settings": {
"terminal.integrated.cwd": "C:\\MyPython",
"terminal.integrated.env.windows": "C:\\MyPython"
}
}
Again this didn't work.
File Structure
My file structure is as follows:
C:\MyPython
.env
MyProject.code-workspace
test.py
Pkg\
__init__.py
Class1.py
Class2.py
If I use the green triangle button ("Run File in Python Terminal") to run test.py then that file's directory (C:\MyPython) gets added to sys.path and everything works (e.g. import Pkg.Class1 works).
However if I run Class2.py (which includes import Pkg.Class1 in the code and doctest) then instead the directory C:\MyPython\Pkg gets added to sys.path and it can't find and import the Pkg package and the doctest fails.
As such I want to add C:\MyPython to the python path, regardless of the directory of the file that is being run.
Of course, I could just add all tests to test.py and run that, but I really just want to run the doctests in the class I'm working on, rather than have to run all the tests every time (and flip to another file to do it).
It seems like this should be easy, but I can't get it to work!
Any ideas?
PS: I haven't included the .py code for the test or classes since it's irrelevant to the problem, it's the import that fails. Ultimately I can see that the required directory appears neither in sys.path nor in os.environ.get('PYTHONPATH') and that's why the import fails.
So two things. One, Python is not designed for you to execute files contained within packages, so you're somewhat going against its design trying to make this work. It would be better to do something like use Python's -m flag to do what you want, e.g. python -m Pkg.Class2. That way you don't have to manipulate your paths to run a module contained in your package.
Two, you were very close in getting what you were after with your settings, but you accidentally used a string instead of an object for specifying your environment variables for your terminal. What you wanted was:
"terminal.integrated.env.windows": {"PYTHONPATH": "C:\\MyPython"}

Pylint "unresolved import" error in Visual Studio Code

I am using the following setup
macOS v10.14 (Mojave)
Python 3.7.1
Visual Studio Code 1.30
Pylint 2.2.2
Django 2.1.4
I want to use linting to make my life a bit easier in Visual Studio Code. However, for every import I have states "unresolved import". Even on default Django imports (i.e. from django.db import models).
I presume it is because it is not seeing the virtual environment Python files.
Everything works just fine, but it's starting to get annoying.
The interpreter choices I have are all system versions of Python. It does not seem to see my virtual environment Python at all (it is not in the same directory as my workspace, so that part makes sense).
If I set up the python.PythonPath in the settings.json file, it just ignores it and does not list my virtual environment path as an option. I also tried setting it up in my global Python settings, but it also does not show up.
Is there a quick fix to get it working?
The accepted answer won't fix the error when importing own modules.
Use the following setting in your workspace settings .vscode/settings.json:
"python.autoComplete.extraPaths": ["./path-to-your-code"],
Reference: Troubleshooting, Unresolved import warnings
In your workspace settings, you can set your Python path like this:
{
"python.defaultInterpreterPath": "/path/to/your/venv/bin/python",
}
Alternative way: use the command interface!
Cmd/Ctrl + Shift + P → Python: Select Interpreter → choose the one with the packages you look for:
This issue has already been opened on GitHub:
Python unresolved import issue #3840
There are two very useful answers, by MagnuesBrzenk and SpenHouet.
The best solution for now is to create a .env file in your project root folder. Then add a PYTHONPATH to it like this:
PYTHONPATH=YOUR/MODULES/PATH
And in your settings.json add:
"python.envFile": ".env"
When I do > reload window that fixes it.
Reference: Python unresolved import issue #3840, dkavraal's comment
None of the solutions worked except this one. Replacing "Pylance" or "Microsoft" in the settings.json solved mine.
"python.languageServer": "Jedi"
You need to select the interpreter associated with the virtual environment.
Click here (at the bottom status bar):
And just select the virtual environment you are working with. Done.
Sometimes, even with the interpreter selected, it won't work. Just repeat the process again and it should solve it.
If you have this code in your settings.json file, delete it:
{
"python.jediEnabled": false
}
If you are more visual like myself, you can use the Visual Studio Code configurations in menu File → Preferences → Settings (Ctrl + ,). Go to Extensions → Python.
In the section Analysis: Disabled, add the suppression of the following message: unresolved-import:
I was able to resolved this by enabling jedi in .vscode\settings.json
"python.jediEnabled": true
Reference from https://github.com/Microsoft/vscode-python/issues/3840#issuecomment-456017675
I wonder how many solutions this problem have (or have not), I tried most of the above, nothing worked, the only solution that worked is to set the python language server to Jedi, instead of Microsoft in the settings.json file:
"python.languageServer": "Jedi"
None of the previous answers worked for me. Adding both of the lines below to my settings.json file did, however.
"python.analysis.disabled": [
"unresolved-import"
],
"python.linting.pylintArgs": ["--load-plugin","pylint_protobuf"]
The first line really just hides the linting error. Certainly not a permanent solution, but de-clutters the screen.
This answer gave me the second line: VS Code PyLint Error E0602 (undefined variable) with ProtoBuf compiled Python Structure
Maybe someone who understands Python more than me can explain that one more.
Okay, so 2 years down the line, I have ran into this annoying problem. All I can seen here are some really complicated workarounds. Here are easy to follow steps for anyone else who might just run into this later on:
at the bottom of VS Code where you see the Python version listed, just click there
Select Interpreter windows is going to appear
click on the first option that says "Select Interpreter Path" and navigate to the folder path which has your Virtual Environment
That's all you need to do and avoid tampering with those settings in VS Code which might get very complicated if not handled with caution.
My solution
This solution is only for the current project.
In the project root, create folder .vscode
Then create the file .vscode/settings.json
In the file setting.json, add the line (this is for Python 3)
{
"python.pythonPath": "/usr/local/bin/python3",
}
This is the example for Python 2
{
"python.pythonPath": "/usr/local/bin/python",
}
If you don't know where your Python installation is located, just run the command which python or which python3 on the terminal. It will print the Python location.
This example works for dockerized Python - Django.
I was facing the same problem while importing the project-related(non standard) modules.
Detailed explanation of the problem
Directory structure:
Project_dir:
.vscode/settings.json
dir_1
> a
> b
> c
dir_2
> x
> y
> z
What we want:
Project_dir
dir_3
import a
import y
Here "import a" and "import y" fails with following error:
Import "dir_1.a" could not be resolvedPylancereportMissingImports
Import "dir_2.y" could not be resolvedPylancereportMissingImports
What worked for me:
Appending the top directory which contains the modules to be imported.
In above example add the follwoing "Code to append" in ".vscode/settings.json"
Filename:
.vscode/settings.json
Code to append:
"python.analysis.extraPaths": [dir_1, dir_2]
The solution from Shinebayar G worked, but this other one is a little bit more elegant:
Copied from Python unresolved import issue #3840:
Given the following example project structure:
workspaceRootFolder
.vscode
... other folders
codeFolder
What I did to resolve this issue:
Go into the workspace folder (here workspaceRootFolder) and create a .env file
In this empty .env file, add the line PYTHONPATH=codeFolder (replace codeFolder with your folder name)
Add "python.envFile": "${workspaceFolder}/.env" to the settings.json
Restart Visual Studio Code
To me the problem was related with the project that I was working on. It took me a while to figure it out, so I hope this helps:
Original folder structure:
root/
__init__.py # Empty
folder/
__init__.py # Empty
sub_folder_b/
my_code.py
sub_folder_c/
another_code.py
In another_code.py:
from folder.sub_folder_b import my_code.py
This didn't trigger the intellisense in Visual Studio Code, but it did execute OK.
On the other hand, adding "root" on the import path, did make the intellisense work, but raised ModuleNotFoundError when executing:
from root.folder.sub_folder_b import my_code.py
The solution was to remove the _init_.py file inside the "folder" directory, leaving only the _init_.py located at /root.
This works for me:
Open the command palette (Ctrl + Shift + P) and choose "Python: Select Interpreter".
Doing this, you set the Python interpreter in Visual Studio Code.
None of the answers here solved this error for me. Code would run, but I could not jump directly to function definitions. It was only for certain local packages. For one thing, python.jediEnabled is no longer a valid option. I did two things, but I am not sure the first was necessary:
Download Pylance extension, change python.languageServer to "Pylance"
Add "python.analysis.extraPaths": [ "path_to/src_file" ]
Apparently the root and src will be checked for local packages, but others must be added here.
I am using the following setup: (in Apr 2021)
macos big sur
vscode
Anaconda 3 (for environment)
And I faced this error during starting of the Django.
So, I follow these steps and this error is resolved.
Steps are given in these screenshots:
Open settings (workspace)
Follow this screenshot to open Python Path
Now, click Edit in settings.json
Make path like given in this screenshot /opt/anaconda3/bin/python
5. Now, save this settings.json file.
6. Restart the vscode
Also, intellisense might not work for some time hold on wait for some time and then restart again then vscode reads file for new path.
That happens because Visual Studio Code considers your current folder as the main folder, instead of considering the actual main folder.
The quick way to fix is it provide the interpreter path to the main folder.
Press Command + Shift + P (or Ctrl + Shift + P on most other systems).
Type Python interpreter
Select the path where you installed Python in from the options available.
Changing
Python:Language Server
to 'Jedi' worked for me.
It was 'Windows' initially.
For me, it worked, if I setup the paths for python, pylint and autopep8 to the local environment paths.
For your workspace add/change this:
"python.pythonPath": "...\\your_path\\.venv\\Scripts\\python.exe",
"python.linting.pylintPath": "...\\your_path\\.venv\\Scripts\\pylint.exe",
"python.formatting.autopep8Path": "...\\your_path\\.venv\\Scripts\\autopep8.exe",
Save and restart VS Code with workspace.
Done!
I have a different solution: my Visual Studio Code instance had picked up the virtualenv stored in .venv, but it was using the wrong Python binary. It was using .venv/bin/python3.7; using the switcher in the blue status bar.
I changed it to use .venv/bin/python and all of my imports were resolved correctly.
I don't know what Visual Studio Code is doing behind the scenes when I do this, nor do I understand why this was causing my problem, but for me this was a slightly simpler solution than editing my workspace settings.
In case of a Pylint error, install the following
pipenv install pylint-django
Then create a file, .pylintrc, in the root folder and write the following
load-plugins=pylint-django
I have faced this problem in three ways. Although for each of them a solution is available in the answers to this question, I just thought to put it all together.
First I got an "Unresolved Import" while importing some modules and I noticed that my installations were happening in global pip instead of the virtual environment.
This issue was because of the Python interpreter. You need to select the interpreter in Visual Studio Code using Shift + Ctrl + P and then type Select Python Interpreter. Select your venv interpreter here.
The second issue was: The above change did not resolve my issue completely. This time it was because of file settings.json. If you don't have the settings.json file in your project directory, create one and add the following line in that:
{
"python.pythonPath": "apis/bin/python"
}
This will basically tell Visual Studio Code to use the Python interpreter that is in your venv.
The third issue was while importing a custom Python module or file in another program. For this you need to understand the folder structure. As Python in venv is inside bin, you'll need to specify the folder of your module (most of the time the application folder). In my case it was app,
from app.models import setup_db
Verbally, import setup_db from models.py resides in the app folder.
If you are using pipenv then you need to specify the path to your virtual environment.in settings.json file.
For example :
{
"python.pythonPath":
"/Users/username/.local/share/virtualenvs/Your-Virual-Env/bin/python"
}
This can help.
If someone happens to be as moronic as me, the following worked.
Old folder structure:
awesome_code.py
__init__.py
src/
__init__.py
stuff1.py
stuff2.py
New structure:
awesome_code.py
src/
__init__.py
stuff1.py
stuff2.py
How to avoid warning
Please note that this is just skipping the warning not resolving it.
First of all open visual studio code settings in json and add following arguments after "[python]":{}
"python.linting.pylintArgs": ["--rep[![enter image description here][1]][1]orts", "12", "--disable", "I0011"],
"python.linting.flake8Args": ["--ignore=E24,W504", "--verbose"]
"python.linting.pydocstyleArgs": ["--ignore=D400", "--ignore=D4"]
This has helped me to avoid pylint warnings in VSCode.
I have resolved import error by Ctrl + Shift + P.
Type "Preferences settings" and select the option Preferences Open Settings (JSON)
And add the line "python.pythonPath": "/usr/bin/"
So the JSON content should look like:
{
"python.pythonPath": "/usr/bin/"
}
Keep other configuration lines if they are present.
This should import all modules that you have installed using PIP for autocomplete.

Visual Studio Code Python import paths

Is it possible to automate or relocate a launch.json setting to the user settings so I do not have to edit the same line in each launch.json?
I have many Python modules in a directory outside of the Python Path and currently am having to edit each launch.json file to add the following line:
"env": {"PYTHONPATH": "\\my\\custom\\path"}
I tried adding the following line to User Settings, but it did not work:
"python.envFile": "\\path\\to\\python\\env\\file"
where the *.env contains the following:
"PYTHONPATH": "\\my\\custom\\path"
VScode I can open any python file that import from a custom path, right click and run it through VScode - I assume VScode is calling the native Python interpreter and seeing the PYTHONPATH environment variable.
Some Python environments (Spyder, PyCharm, etc) have a global setting for this, but I do not know how to accomplish this in VScode. Note VScode is consistent with PTVS; I have to edit the Search Paths for each Python solution in Visual Studio.

Categories

Resources