Why VSCode fails executing my main module in the new VSCode update? - python

**********New post edition with a simple example********************
After the suggestion of Martineau, I tried a simplified example python program in the following.
The background was that last week Vscode asked me to update to VSCodeUserSetup-x64-1.31.1 in Win10.
So I did.
Then sometimes VSCode failed to execute my main module.
I tried to reinstall and uninstall vscode. I also tried to modify the path variables here and there.
But the problem is still there.
Still I can execute the program OK purely in the console.
The simplified python program is the following.
print ("Here I am!")
The launch.json file is the following.
{
"version": "0.2.0",
"configurations": [
{
"name": "vsCode Test ",
"type": "python",
"request": "launch",
"stopOnEntry": true,
"pythonPath": "${config:python.pythonPath}",
"program": "${workspaceRoot}/src/pt.py",
"args": [
],
"cwd": "${workspaceRoot}",
"env": {},
"envFile": "${workspaceRoot}/.env",
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit",
"RedirectOutput"
]
}
]
}
After I clicked the debugger button and then the right triangle button to execute the debugger, I always got the following screenshot which showed that nothing was executed.
I suspect that the new update has changed my settings in vscode.
But I don't know where to reconfig vscode.
Your help will be deeply appreciated!
Thanks
Farn
****************Old post with a more complicate example!****************
dear all:
Last week Vscode asked me to update to VSCodeUserSetup-x64-1.31.1.
So I did.
Then sometimes VSCode stopped to execute my main module.
The basic screen layout is the following.
VSCode basically stalled before the first statement and the first breakpoint.
But if I use Console to execute "python CnTaaD.py -L", the module (CnTaaD.py) executed correctly.
I tried several times and even reinstall, uninstall, used an older version of VSCode.
The stalling problem came on and off.
Then last night, VSCode always stalled before the first statement and the first breakpoint.
My friend helped me and guessed it is because the path to python interpreter is wrong now.
But we tried to set the path variables here and there.
Nothing good happened.
The code of CnTaaD.py is in the following for your reference.
It calls another module.
Can anyone help by telling me how to reconfigure maybe VSCode so that I can resume the development ?
Thanks
from __future__ import print_function # (at top of module)
if __name__ == '__main__':
import os
import sys
import CnUserManager
if sys.version_info[0] < 3: # Python 2 and 3:
print ("python 2.x")
# to execute the file, type in the following command in powershell:
# % python CnTaaDPackage.py build_ext --inplace
import future # pip install future
import builtins # pip install future
import past # pip install future
import six # pip install six
else:
print ("python 3.x")
root = os.path.realpath(__file__)
# print ("realpath of __file__ is ", root)
root = os.path.dirname(root)
root = os.path.dirname(root)
sys.argv.append(root)
# print ("sys.argv = ", sys.argv)
CnUserManager.CnUserManagerClass(sys.argv)

I kind of solved the problem.
Basically, I removed the "RedirectOutput" option from the "debugOptions" in launch.json. Somehow, the older version the redirection is to the console in the debug screen.
But now I am not sure where it is to.
In fact, there are three consoles in VSCode, internal, integrated, and external.
I will appreciate it if someone can enlighten me which is which ?
I checked some related pages. But vague explanations are found.

Related

Python Extensions cannot see installed packages in DevContainer IDE

I am trying to create a basic Development Container to use with VS Code.
I've been through a few iterations no of versions but keep coming up against the same issue, my VS Code extensions cannot seem to see what packages are installed in my venv.
Files in my workspace:
.devcontainer/devcontainer.json
{
"name": "Existing Dockerfile",
"context": "..",
"dockerFile": "../Dockerfile"
}
venv/ containing pip installed pandas
Dockerfile:
FROM python:3.9
WORKDIR .
COPY my_file.py .
my_file.py
import sys
import pandas
print(sys.path)
Output of sys.path incase relevant is ['/workspaces/yt', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/workspaces/yt/venv/lib/python3.9/site-packages']
The code executes fine when ran but in VS Code the linting tools raise an error that pandas is not accessed.
Any help would be greatly appreciated.
The most likely reason is that the environment in which the pandas library was installed is not the same as the environment you are currently using.
Solution
Use Ctrl+Shift+P to open the command palette and search for Python:Select Interpreter to select a correct interpreter.
If the error is still not resolved, go ahead and try the following methods:
Add configuration in settings.json to point to the pandas library.
// Just an example, please modify it to your own path
"python.analysis.extraPaths": [
// Path to pandas library
"C:\\WorkSpace\\PyTest0802\\.venv\\Lib\\site-packages"
],
The most simple and rude method -- cancel this type of error (use with caution, this method will cause the prompt message that there is such an error to not be displayed)
Add the following configuration to the settings.json file
"python.analysis.diagnosticSeverityOverrides": {
"reportMissingModuleSource": "none",
},

Python debugger can't find module

I am building an application in Python. A while ago, I was able to debug it without any issues, but after accidently reseting my VS Code settings, I am not able anymore. Whenever I try to debug I get the following error on the first installed library I try to import:
Exception has occurred: ModuleNotFoundError No module named
'PySimpleGUI'
When I try to install the library using pip3, I get the message:
Requirement already satisfied: PySimpleGui in c:\users\adassa\appdata\local\packages\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\localcache\local-packages\python39\site-packages
When I run directly from the console using python3 name_of_file.py, the file runs without any problems. Here is my launch.json for debugging:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"env": { "PYTHONPATH": "${workspaceRoot}"}
}
]
}
I read in other questions that this error has to do with different installations of Python, and the debugger trying to find the library on the wrong directory, but couldn't understand how to solve it.
I tried replacing PYTHONPATH with the path of python3 I get from the console. (I obtaineed that path using the command from this answer: https://stackoverflow.com/a/647798/14874778, but the error remains. How can I solve this problem?
Do you have multiple python installations? If so, try something that looks like this (made for python 3.7.9 & Windows):
py -3.7 -m pip install pysimplegui
This has always worked for me.
You can also try specifying which installation you want to run the script, which should look like this (also 3.7.9, also Windows):
py -3.7 helloworld.py

VS Code Python Debugger "timed out waiting for debuggee to spawn"

My debugger doesn't even begin to run my code. I press F5, the debug tab opens, shows that it is loading, and after a while it says "Session-1 timed out waiting for debuggee to spawn" in a pop-up window. I'm using VS Code version 1.40.1, I have my virtual environment setup, and the debugger used to work, stopping at breakpoints and changing the color of the blue bar at the bottom of the screen. Issue appeared while messing with the open() function, but the debugger doesn't work with any file.
I have seen and tried the solutions offered here and here. I don't use Conda, Jupyter, or any extensions besides the standard Python extension.
Code:
import os
def fib(n):
if not os.path.exists("Fibfile.txt"):
with open("Fibfile.txt", "w") as file:
file.write("1\n2\n")
with open("Fibfile.txt", "r") as file:
contents = file.readlines()
data = []
for item in contents:
# removes newline
data.append(int(item[:-1]))
with open("Fibfile.txt", "a") as file:
if n <= len(data):
return
else:
while n > len(data):
data.append(data[-2]+data[-1])
file.write(f"{data[-1]}\n")
fib(100)
My launch.json:
{
// 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: Arquivo Atual",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}
My solution is downgrade Python extension for Visual Studio Code.
You can download from GitHub release.
PTVSD release 2019.10.44104 is fine with VS Code 1.40.2.
Unchecked Extensions: Auto Update/Auto Check Updates
and install from VSIX manually.
Update: Newer version VS Code 1.41 fix this issue already.
the python version is conflict with python debugger version.
Change an older python debugger version or python version.

VS Code - pylinter cannot find module

I started using VS Code for Python development on a Mac and cannot make pylint find a module.
This is my project folder structure:
project_root/
.env
.vscode/
settings.json
lib/
# lib containing necessary modules
sample/
client/
EDAMTest.py
# many more files
I use a virtualenv in which I have installed pylint. The virtual env is activated in the terminal. I started code from within project_root folder via code . in my terminal.
VS Code says it is using the correct interpreter. I can see on the bottom left that it says Python 3.6.1 (virtualenv)
If I want to test the project_root/sample/client/EDAMTest.py code within terminal I can do it via export PYTHONPATH=../../lib; python EDAMTest.py while being in folder project_root/sample/client/.
Now if I am in VS Code, open the file EDAMTest.py, pylint is telling me that it cannot import modules from lib.
Now my question:
How can I add lib to PYTHONPATH in VS Code?
I found several possible ways to do so:
Create a .env file (see [1] below).
Specify PYTHONPATH in .vscode/launch.json file (see [2])
None of the possible solutions I found seem to work.
What am I missing?
[1] Environment variable definitions file
This tells me how to define global (env) vars. So I specified this:
PYTHONPATH="~/.virtualenvs/evernote/bin/python;lib"
But it won't work. Still libs path is not found by pylint
[2] So I did create a launch.json file like so:
{
"name": "Python",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"pythonPath": "${config.python.pythonPath}",
"program": "${file}",
"cwd": "${workspaceRoot}",
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit",
"RedirectOutput"
],
"env": {
"PYTHONPATH": "~/.virtualenvs/evernote/bin/python:lib"
}
}
---
EDIT
Here is a link that tries to address this problem:
Troubleshooting linting
That link tries to address several possible problems, one is this:
... unable to import
The suggested solution is:
Ensure that the pythonPath setting points to a valid Python installation where Pylint is installed.
=> Yes, I did.
Alternately, set the python.linting.pylintPath to an appropriate version of Pylint for the Python interpreter being used.
=> I did, still no success:
My .vscode/settings.json:
{
"python.pythonPath": "~/.virtualenvs/evernote/bin/python",
"python.linting.pylintPath": "~/.virtualenvs/evernote/bin/pylint"
}
It seems that I had to use a colon instead of a semicolon in .env file like so: PYTHONPATH="~/.virtualenvs/evernote/bin/python:lib". That seems to solve the problem.

Visual Studio Code - How to add multiple paths to python path?

I am experimenting with Visual Studio Code and so far, it seems great (light, fast, etc).
I am trying to get one of my Python apps running that uses a virtual environment, but also uses libraries that are not in the site-package of my virtual environment.
I know that in settings.json, I can specify a python.pythonPath setting, which I have done and is pointing to a virtual environment.
I also know that I can add additional paths to python.autoComplete.extraPaths, where thus far I am adding the external libraries. The problem is, when I am debugging, it's failing because it's not finding the libraries specified in python.autoComplete.extraPaths.
Is there another setting that must be used for this?
Thanks
This worked for me:-
in your launch.json profile entry, specify a new entry called "env", and set PYTHONPATH yourself.
"configurations": [
{
"name": "Python",
"type": "python",
"stopOnEntry": false,
"request": "launch",
"pythonPath": "${config.python.pythonPath}",
"program": "${file}",
"cwd": "${workspaceRoot}",
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit",
"RedirectOutput"
],
"env": {
"PYTHONPATH": "/path/a:path/b"
}
}
]
The Python Extension in VS Code has a setting for python.envFile which specifies the path to a file containing environment variable definitions (Refer to: https://code.visualstudio.com/docs/python/environments#_environment-variable-definitions-file). By default it is set to:
"python.envFile": "${workspaceFolder}/.env"
So to add your external libraries to the path, create a file named .env in your workspace folder and add the below line to it if you are using Windows:
PYTHONPATH="C:\path\to\a;C:\path\to\b"
The advantage of specifying the path here is that both the auto-complete as well as debugging work with this one setting itself. You may need to close and re-open VS Code for the settings to take effect.
I had the same issue, malbs answer doesn't work for me until I change semicolon to a colon,you can find it from ZhijiaCHEN's comments
"env": { "PYTHONPATH": "/path/to/a:/path/to/b" }
Alternatively, I have a hack way to achieve the same:
# at the top of project app script:
import sys
sys.path.append('/path/to/a')
sys.path.append('/path/to/b')
You could add a .pth file to your virtualenv's site-packages directory.
This file should have an absotute path per line, for each module or package to be included in the PYTHONPATH.
https://docs.python.org/2.7/install/index.html#modifying-python-s-search-path
Based on https://github.com/microsoft/vscode-python/issues/12085, I added the following to the settings portion of the workspace config file. I'm using Linux. For Windows, use terminal.integrated.env.windows.
"terminal.integrated.env.linux": {
"PYTHONPATH": "addl-path-entry1:addl-path-entry2"
}
I also added an .env file as described by many posts/comments above.
Finally, I added the PyLance extension per https://stackoverflow.com/a/64103291/11262633.
I also reloaded my workspace.
These two changes allowed me to run Python programs using the debugger and the Run menu. AutoComplete is aware of the added path, and my VSCode linter (was the default linter pylint, now ``pylance```) now works.
I made it work through adding "python.analysis.extraPaths" when using Pylance and IntelliCode.
In 2022, the configuration is as file .vscode/settings.json:
{
"python.analysis.extraPaths": ["C:/Program Files/obs-studio/data/obs-scripting/64bit"],
"terminal.integrated.env.windows": {
"PYTHONPATH": "C:/Program Files/obs-studio/data/obs-scripting/64bit;${env:PYTHONPATH}",
"PATH": "C:/Program Files/obs-studio/data/obs-scripting/64bit;${env:PATH}"
}
}
bash escamotage (works with debugger AND autocomplete); need to install code command in PATH (vsc shell command: install...)
#!/bin/bash
#
# vscode python setup
#
function fvscode {
# you just want one of this:
export PYTHONPATH=<your python installation ../bin/python3>
# you may want many of these:
export PYTHONPATH=<your lib dir here>:$PYTHONPATH
# launch vscode
code
}
alias vscode='fvscode'
the launch VSC by typing 'vscode'.
According to the environments doc, the places the extension looks for environments include some defaults and also the setting value for python.venvPath in the workspace settings
eg: "python.venvPath": "~/.virtualenvs"
This allows you to find several (eg: virtualenvs) as mentioned:
To select a specific environment, use the Python: Select Interpreter
command from the Command Palette

Categories

Resources