From what I found in the community, there are two options to extend the Python search path with further libraries.
.env
e.g. PYTHONPATH="C:\path\to\a;C:\path\to\b"
launch.json
e.g.
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": true,
"env": {
"PYTHONPATH": "${workspaceFolder}/lib"
}
}
]
}
After searching again for this topic on multiple days, I did not yet find any clear solution for that.
Some things work as expected, others don't. To be clear, it might be just a wrong understanding of the
concepts. Since I found multipe threads on the topic, but almost just the same answers, which did not
yet work out for me. There are multiple threads aroung that stuff, so I assume some general interest for a clarification.
Currently I tested exlusively each option. Using both things in parallel is somehow not comfortable,
also since the capabilities are different. .env does not support pre-defined variables,
lauch.json, does. So I tested .env without settings in launch.json and no .env file + settings in launch.json.
I use VS Code 1.75.1, but it was the case also for multiple previous version.
Anaconda Python3 with different virtual environments.
What I see is the following, when using the options in VS Code:
yes --> extending the PYHTONPATH worked as expected
no --> extending the PYHTONPATH dir NOT worked as expected
Run option
.env setting
launch.json setting
Run Python file in terminal
no
no
Run in interactive Window
yes
no
Debug via F5
yes
yes
"Debug Python File" (*)
yes
no
(*) Debug via "Debug Python File" in Drop-Down of Run Symbol above right of the editor window
I assumed both debug options should be the same, but I have sometimes situations, where starting Debug via F5 works as expected, but using the Debug Symbol reports an error.
Not clear, why both debug options behave differently.
No idea, why running Python terminal, does ignore path settings completely.
In general more detailed information about the ideas behind both optios, would be very helpful. Why there is a difference for just running code in the terminal and debugging. The concept of launch configurations I know from other IDEs and it makes a lot of sense to me. Is there a way define such conigurations hiarchically, so only changes have to be added for lower levels and the rest can be kept common.
Setting all environment stuff on OS/command shell level, is possible via system/user variables. But I thought, that VS Code is doing that specifically for each workspace/project.
What am I doing wrong? What do have I missed during setup of VS Code? Or where do I not yet understand the concecept/workflow correctly.
I expected to control the library path settings for each workspace seperately. Potenitally in just one place (one configuration setting) in the workspace area (.env or launch.jason, or what ever other way)
Any help/comment is appreciated, thanks a lot,
Mike
For the questions raised in your article, if you're only interested in debugging a Python script, the simplest way is to select the down-arrow next to the run button on the editor and select Debug Python File.
If you're looking to debug a web application using Flask, Django or FastAPI, the Python extension provides dynamically created debug configurations based on your project structure under the Show all automatic debug configurations option, through the Run and Debug view(f5).
You can read document basic-debugging for more detials.
I expected to control the library path settings for each workspace
seperately.
I suggest you using virtual environment. This makes it easier for you to manage your library.
In addition, if you want to import the package in the specified location, you can use env in the launch.json file:
"env": {
"PYTHONPATH": "path/to/your/package"
}
In vscode, when I hover on a python keyword, a tooltip showing the definition of the keyword appear.
I also have pylint installed, and I want to keep the tooltip for showing pylint error but disable it for the python keyword definition. Is there any way to do that ?
By setting the language service to Microsoft in the settings.json file of vscode, the definition of python keywords disappear.
It does not really answer the question I asked, but it is enough for my needs.
I have started using Python and Django and I am very new in this field.
And this is my first time to ask a question here...I do apologise in advance if there is a known solution to this issue...
When I installed and set VSCode formatter 'black' (after setting linter as flake8), the tutorial video tutor's side shows up pop-up like 'formatter autopep8 is not installed. install?'. & Mine did not show up that message.
So what I did was...
manually input 'pipenv install flack --dev --pre' on terminal.
manually input "python.formatting.provider": "black", to 'settings.json' on '.vscode' folder.
Setting(VSCode) -> flake8, Python > Linting: Flake8 Enabled (Also modified in: workspace), (ticked the box) Whether to lint Python files using flake8
The bottom code is from settings.json (on vscode folder).
{
"python.linting.pylintEnabled": false,
"python.linting.flake8Enabled": true,
"python.linting.enabled": true,
"python.formatting.provider": "black", # input manually
"python.linting.flake8Args": ["--max-line-length=88"] # input manually
}
I found a 'black formatter' document. https://github.com/psf/black & it stated...
python -m black {source_file_or_directory} & I get the following error message.
Usage: __main__.py [OPTIONS] [SRC]...
Try '__main__.py -h' for help.
Error: Invalid value for '[SRC]...': Path '{source_file_or_directory}' does not exist.
Yes, honestly, I am not sure which source_file_or_directory I should set...but above all now I am afraid whether I am on the right track or not.
Can I hear your advice? At least some direction to go, please.
Thanks..
I use Black from inside VSCode and it rocks. It frees mental cycles that you would spend deciding how to format your code. It's best to use it from your favorite editor. Just run from the command line if you need to format a lot of files at once.
First, check if you have this in your VSCode settings.json (open it with Ctrl-P + settings):
"python.formatting.provider": "black",
"editor.formatOnSave": true,
Remember that there may be 2 setting.json files: one in your home dir, and one in your project (.vscode/settings.json). The one inside the project prevails.
That said, these kind of problems usually are about using a python interpreter where black isn't installed. I recommend the use of virtual environments, but first check your python interpreter on the status bar:
If you didn't explicitly select an interpreter, do it now clicking on the Python version in your status bar. You can also do it with Ctrl-P + "Python: Select Interpreter". The status bar should change after selecting it.
Now open a new terminal. Since you selected your interpreter, your virtual environment should be automatically activated by VSCode. Run python using your interpreter path and try to import black:
$ python
Python 3.7.3 (default, Mar 27 2019, 22:11:17)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import black
>>>
Failed import? Problem solved. Just install black using the interpreter from the venv: python -m pip install black. You also can install using Conda, but in my experience VSCode works better with pip.
Still not working? Click in the "OUTPUT" tab sibling of the TERMINAL and try to get more info at the "Log" output. Select it in the pull down menu:
Attach my finding for those who still can't solve the Black formatting issue in VS Code.
First, you have to install Black globally or locally (if you use virtual env like conda).
Then, make sure your VS settings as following, set python default formatter provider as 'black':
Finally, open settings.json of your VS Code, add the following segment for it.
"[python]": {
"editor.defaultFormatter": null,
"editor.insertSpaces": true,
"editor.tabSize": 4,
"editor.formatOnSave": true
}
The key point is:
"editor.defaultFormatter": null
If you still use "editor.defaultFormatter": "black" as many old posts suggest, the Black formatter will not work in newer VS Code.
Like camab said, you can totally run it from the command line:
$ black file.py
You can also run it on a whole folder (directory) of python files:
ex if I have:
src/
| - module/
| | - moduleFile.py
| \ - __init__.py
|
\ - script.py
and run
$ black src
it would format moduleFile.py, __init__.py, and script.py.
As far as your VSCode config goes, I also like to have in settings.json
{
"editor.formatOnSave": true,
"python.linting.lintOnSave": true,
}
to make sure that every time I press save the file is getting linted and formatted.
If you ever have issues with linting/formatting in VSCode you can use the "Command Palette" (Ctrl+Shift+P) to force the following commands:
Python: Run Linting
Python: Select Linter
Format Document
Format Document With...
Which should produce a visual pop-up style error if there's actually a problem.
Hope this helps and happy coding!
For those who have tried it all :).
Black will not work in VSCode if you have
a syntax error,
an IPython magic (e.g., %matplotlib inline).
Running black from the terminal on the file reveals these issues.
For those who see this and none of the above solutions work.
If you set the black path to its absolute location it might solve the problem.
There is a new extension, currently pre-release, for formatting with black. See v1.67 Release Notes, Python Black formatting.
From the README (vscode Marketplace: Black Formatter):
Usage
Once installed in Visual Studio Code, "Black Formatter" will be available as a formatter for python files. Please select "Black Formatter" (extension id:ms-python.black-formatter) as the default formatter. You can do this either by using the context menu (right click on a open python file in the editor) and select "Format Document With...", or you can add the following to your settings:
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter"
}
Format on save
You can enable format on save for python by having the following values in your settings:
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter",
"editor.formatOnSave": true
}
Another possibility is that you have added incorrectly formatted black arguments. The plugin wants every space-separated option to be added as a it's own "item" in the Settings UI like so:
You should be able to see the args pass through correctly into the Output->Python console like so:
It should not look like this:
Probably you have conflicts with your default formatter just add "[python]": { "editor.defaultFormatter": null } to your Open User Settings in VSC.
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"python.formatting.provider": "black",
"[python]": { "editor.defaultFormatter": null }
I had that same problem and only cure was to remove
"python.formatting.blackArgs": ["--skip-numeric-underscore-normalization"],
from setting.json. It doesn't make sense but it works.
For me the problem was not black directly, but an invalid project settings file that it reads to find config settings. The root cause was not logged anywhere.
I found the cause by checking the OUTPUT tab with Python extension selected. It showed black being called with apparently no problems reported:
./.venv/bin/python -m black --diff --quiet ./myfile.py
cwd: .
However when I ran the same command in the terminal I got the error reported:
Error: Could not open file './pyproject.toml': Error reading configuration file: Invalid value (at line 18, column 10)
When this was fixed I could format my code manually and format on save was back too.
If you are using windows operating system, then there is a simplest solution:
Find out where you have installed black package. It can be on AppData/python/scripts
Click on start menu and type "Edit the system environment variables" and select it.
now click on environment variable and double click on 'path' from 'System Variable' portion to edit.
now add the package path here like "Appdata/path/scripts;"
Hopefully now black will work fine on every save.
This solution works fine for me.
Note: Now you can use black from CLI.
Yet another reason that black may stop working when run from vs code...
Perhaps you have started using Python 3.10
Black will fail if new features like Structural Pattern Matching are used. VS Code fails silently. No formatting happens. It appears that black isn't working.
Try running black from the command line to see if there are error messages.
This is what I got:
$ black my_code.py
error: cannot format my_code.py: Cannot parse: 57:14: match rec.split():
Consider using --target-version py310 to parse Python 3.10 code.
Oh no! 💥 💔 💥
1 file failed to reformat.
I had to add --target-version=py310 to VS Code's blackArgs, like this:
"python.formatting.blackArgs": ["--target-version=py310"]
Note the equals (=) sign.
Nothing in this question worked for my black. I gave up and switched default formatter in Settings > UI to autopep8 instead and everything worked.
If you are working on dev container then you might need to install Black Formatter extension. It worked for me, here is the link:
https://marketplace.visualstudio.com/items?itemName=ms-python.black-formatter
Another possibility is that a syntax error is preventing Black from working. Black will not apply any formatting changes if there is a syntax error.
However, VS Code still displays "Formatting with Black" in the status bar and silently fails.
You can verify this by running Black from the command line, which will show the error if there is one:
$ black foo.py
error: cannot format foo.py: Cannot parse: 328:4: :
Oh no! 💥 💔 💥
1 file failed to reformat.
The best way to use black is through terminal in my opinion. All you need to do is install it on pip on terminal using: pip install black
Then when it's installed you go onto terminal and type: black filename.py
the full line would be: black filepath/file.py
So for a file called test.py located on desktop if on mac: black desktop/test.py
If you want to do it on multiple files than do it individually to each file.
I'm trying to make Visual Studio Code detect unused Python imports. One of the ways is to type "editor.showUnused": true into the setting.json file.
{
"editor.showUnused": true
}
But it just doesn't work for me, even if I reloaded VSCode. I also went into VSCode settings and checked the box for "control fading out for unused code", which also did not work.
PyCharm automatically fades out unused imports. Is there a way to do the same in VSCode?
{"editor.showUnused": true} is VS Code default setting. The value controls fading out of unused code and decides if the unused modules are displayed solidly:
To fix your question, you can reset the VS Code. Delete everything between the two curly braces in User settings.json, save the file, and VS Code will go back to using the default values.
If the question still exists, it's recommended to uninstall VS Code completely:
Delete all settings: turn to directory \userfolder\AppData\Roaming\Code and delete the whole folder.
Delete all extensions: \userfolder\.vscode\extensions and delete the whole folder.
Then install VS Code again.
When I start a python project in vs code (with the microsoft python extension) it starts "Analyzing in the background" and python keep crashing. It also uses a ton of memory.
Anyone knows how to fix this? Or is it supposed to do this?
This seems to have fixed it for me: https://github.com/Microsoft/vscode-python/issues/4990#issuecomment-477628947
You can disable the new Python Language Server by opening settings in VSCode (Ctrl+, ) and set "python.jediEnabled": true. Then reload the window and/or restart VSCode.
I had the same issue; the only solution that worked for me was to open settings.json (ctrl + Shift + P) and change
"python.languageServer": "Microsoft"
to
"python.languageServer": "Pylance"
Then one gets a pop-up that asks whether one wants to reload the window which one should confirm by pressing "OK".
Then everything works normally again (IntelliJ, autocomplete etc).
As #Vasco pointed out in the comments Microsoft is no longer supported as explained in this thread.
High memory usage: https://github.com/Microsoft/python-language-server/issues/832
Jedi is an autocompletion tool for Python that can be used in IDEs/editors. Jedi works. Jedi is fast. It understands all of the basic Python syntax elements including many builtin functions. So you can switch Jedi instead of Python Language Server.
Process:
set "python.jediEnabled": true
disable the Visual Studio IntelliCode plugin
delete the .vscode directory
Can solve this by either disabling the extension as suggested in previous answers, or excluding large directories (e.g. containing data) from its search path, by adding to your workspace settings an python.workspaceSymbols.exclusionPatterns key, like so:
settings.json:
{
"python.workspaceSymbols.exclusionPatterns": [
"**/site-packages/**",
"your_pattern_or_directory_to_exclude"
]
}
See also the vscode extension docs.
Here is how I solved this issue:
Go to File > Preferences > Settings > TYPE "python.language server"
If set to 'Microsoft' change your language server to 'Pylance'
Python: Language Server
Define Type of the Language Server
SELECT: Pylance
Reload your Visual Studio Code
Try importing your libraries causing the issues again:
import numpy as np
import pandas as pd