VScode python extension does not take changes into account - python-3.x

I am writing a simple script in Python using VS Code. I have the python extension installed and I use a conda environment.
To run my script, I use Shift+Enter (Run Selection in Python Terminal). This works.
However, if I change something in the script and do the same, the change is not taken into account. I am forced to delete the terminal and relaunch again.
Is this normal? How do you guys go at it?

The "Run Selection/Line in Python Terminal" option basically opens a Python console and copies the selected lines to it (as if you typed it yourself). When you make changes to your code and repeat the process, it copies those codes to the same console session, so whatever was copied before, still exists and will be used for next runs. You have to make sure to always run the same set of lines or, as what you are doing now, restart the Python console.
Instead of the "Run Selection/Line in Python Terminal" option, I recommend creating a launch configuration for your script, and then using the debugger.
Let's say you have this workspace:
|- myscript.py
|- .vscode
Start by opening your Python file on the editor, then opening the command palette (Ctrl+Shift+P or CMD+Shift+P), then calling Debug: Open launch.json.
Select Python File for simple scripts. That will automatically create a launch.json file under the .vscode folder, with default launch configurations for Python files. Modify it as needed for running your script. For ex., I prefer setting internalConsole for the console.
{
// 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": "run-myscript",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/myscript.py",
"console": "internalConsole",
"args": [],
"env": {}
}
]
}
Then from the Debug panel, select the launch configuration from the dropdown (same name as the "name" you set in launch.json), then hit the Run button.
Check the output from the Debug Console:
One good thing about this setup is that you can set breakpoints in your code, and then go through your code line-by-line, which is quite useful for debugging.
For more info, see Python debug configurations in Visual Studio Code.

Related

Adding a preTask to launch.json command hides console output

I want to create a task to debug a node proces.
For that it should start a build task.
So I add:
preLaunchTask": "npm: build:main",
On launch, I get the notification that this terminal will be reused by tasks and closing any button will close it.
When I do close it, I do not get a terminal with the debugging output. I only get my regular terminal back.
So I removed the task and launched again to see what happens.
Now no terminal at all opens up and I still only have the default terminal.
Is this a bug or am I doing something wrong?
Note:
presentation is not set in the launch.json command.
Okay this answer fixes it. Adding this to the launch command shows the console again:
"console": "integratedTerminal",
It is weird that you need to specify the console implicitly in this case.

How do I setup launch.json and tasks under Visual Studio Code to fully automate, connect to and debug a remote Python Flask code in Docker container?

There are at least 20 questions that are somewhat related to my question and have contributed to my knowledge of how to solve this problem, but none seem to cover the entire answer to my specific question. Also, it seems that the Microsoft documentation tells you how the parts function, but I have not found a comprehensive example of how to do all of this. I would like this question to cover it all if possible. I have a manual debug process which I will share below, but I want to further automate it with tasks and entries in the launch.json file so that I don't have to start anything manually. Would someone be willing to share their fully automated version of the exact steps in the automation with me?
This is the Configuration steps I followed to make Windows Visual Studio Code to work with the debugpy remote python
debugger. I have also added how to just use an interactive debug session using docker exec -it with pdb as well.
I have both detailed the files that were changed here and what the changes were so that you can understand how it
currently manually works.
Below I have two different ways of running the python debugger:
Run it from the pdb command line interactively from a terminal window:
Run it manually from the command line in a terminal window, but let Visual Studio Code connect to the debugpy program
and Docker container to do it interactively from Visual Studio Code.
The following procedures are adopted from the following 2 articles I found after reading the Visual Studio Code
documentation and after googling how to enable remote Docker Container Python debugging:
Article 1:
https://stackoverflow.com/questions/40233928/how-to-remote-debug-python-code-in-a-docker-container-with-vs-code#:~:text=In%20your%20Docker%20image%2C%20you%27ll%20need%20to%20make,something%20like%3A%20docker%20run%20-d%20-p%203000%3A3000%20my-image
Article 2:
https://code.visualstudio.com/docs/python/debugging#:~:text=Switch%20to%20the%20Run%20and%20Debug%20view%20%28Ctrl%2BShift%2BD%29%2C,which%20point%20you%20can%20use%20the%20debugger%20normally.
To allow the my.py code to use debugpy debugger used by Visual Studio, I added the following entries in the Docker file:
RUN /usr/bin/pip --no-cache-dir install -U debugpy
The procedure to run the pdb debugger manually and interactively from the Ubuntu 20.04 command line is as follows.
Only use this step or step 6 below but not both. This line runs the pdb debugger (not debugpy ) that Visual Studio uses.
At the Ubuntu 20.04 command line execute the following:
export USER=JOHN DIR=/data OUTPUTFILE=/data/output/output.txt
Here is how I run the python program using pdb passing in a call to the run_user module with 3 environment vars:
docker exec -it my_docker_container /usr/bin/python my.py run_user --my_user=$(USER) --my_dir=$(DIR) --my_file=$(OUTPUTFILE)
Now, to support doing debugpy using Visual Studio Code, I add the following 8888:3001 port to the
docker-compose.yml so that it looks as follows after the change:
webapp:
build: ./
image: my.webapp
container_name: my_docker_container
ports:
- 80:80
- 443:443
#----START OF docker-compose.yml changes
- 8888:3001
#----END OF docker-compose.yml changes
depends_on:
- database
Open the Ubuntu 20.04 command prompt
Procedure to run the debugpy remote module on port 3001 internally and 8888 on host machine so that the Visual Studio
debugger can be used. Note: you cannot run both the interactive pdb debugger of step 3 and this step together as it probably won't work and will hang up your machine for a reboot.
Here is how I run the python program manually using debugpy in Visual Studio
export USER="JOHN" DIR=/data OUTPUTFILE=/data/output/output.txt
docker exec -it my_docker_container /usr/bin/python -m debugpy --listen 0.0.0.0:3001 --wait-for-client my.py run_user --user=$(USER) --my_dir=$(DIR) --my_file=$(OUTPUTFILE)
I Add at least the following to the visual studio config in the ~/.vscode/launch.json as follows (.vscode/launch.json) in order to connect to the debugpy backend:
{
// 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: Remote Debug Docker JMK",
"type": "python",
"request": "attach",
"port" : 8888, // This is the localhost port that will be open on your local machine to talk to the debugger.:
"host" : "localhost",
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "/opt/webapp"
}
],
"logToFile": true
}
]
}
After saving the above changes, to the .vscode/launch.json file, you should be able to press Control+Shift+D and then you will have the debugger entry at the top of you screen with a green right arrow. Alternatively, you could press F5 to bring up the debugger window.
If you are not using Visual Studio code and using the interactive pdb debugger,
instead, after you have ran step 3, the debugger will attach and be paused at the first line of code.
You can then use pdb commands and step with next until you get to the next line of code
or you will have to set an initial breakpoint using import pdb pdb.set_trace().
Do not use import pdb or pdb.set_trace() within a Visual Studio Code
debugging session but attach using Visual Studio Code as described in the other steps as the two are
somewhat incompatible with each other because they were developed at different times in Python's history.
Here is where my exact specific question is asked. Not sure why it was flagged by your stupid bot
What is my exact question to the community and how is it different from other questions?
I am not interested in doing the manual steps at step 3 to run either the pdb debugger, nor the debugpy (at step 6) and would like a fully working example of how to set up the tasks and launch.json entries to automatically run the manual steps at step3 and Step 6 within Visual Studio Code.

How to change VS Code Default Terminal to python

I am using Visual Studio Code on my Windows 10 PC. I want to change my default terminal from 'Windows PowerShell' to 'Python' (on Windows). Someone help me solve this issue.
Press Ctrl+Shift+P to bring up the command palette and run the Terminal: Select Default Profile command:
If Python does not appear here, add a profile for it manually in your JSON configuration. Press Ctrl+Shift+P and run the Preferences: Open User Settings (JSON) command:
Add the following lines in your JSON config file and save it:
"terminal.integrated.profiles.windows": {
"Python": {
"path": "python",
"args": []
}
},
Afterwards you should be able to select Python as your default terminal profile.

Configured debug type "python" is not supported for VS Code

I have issues debugging with VS code. I have installed python for vs code extension and reloaded it several time. But when I tried to run in the debug mode, I have the following error
The debug type is not recognized. Make sure that you have a corresponding debug extension installed and that it is enabled.
My launch.json has the following contain
{
// 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 : Fichier actuel",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}
What could be the issue?
I had the same problem and was able to solve it by uninstalling Python and Jupyter Notebook extensions in VS Code and then re-installing them. Note that Jupyter Notebook is now required to use the Python extension in VS Code.
This issue is a VS Code bug, it is being solved in an early Dec-2021 release (v1.63). The warning has no effect whatsoever, there are no real issues running the code.
So, don't pay attention to it, it will be fixed in a short time.
Edit note: Adding, removing, installing, or disabling/enabling the Jupyter Notebook and its related extensions seem to solve the problem but only until the next VS Code restart.
I had this same problem. The easiest way for me to fix it, was to:
go to the Python file in the file explorer,
right click, and choose "run current file in interactive window".
After that selection, VSCode prompted me that
X,Y,Z, will need to be installed and configured".
I did that, and then everything worked just fine!
I had the same problem, but I think it came from using virtualenvwrapper:
when creating virtual environments using mkvirtualenv the virtual environment is not placed inside the project folder (e.g. in a folder .venv), but gathered in a central place defined by the $WORKON_HOME user environment, which has to be defined during installation of virtualenvwrapper.
So far, so good - but VSCode has to be told, where this central folder lies. At least this was what solved the problem for me. So:
open the settings of the Python extension (search for Python (by Microsoft) and click on the gearwheel next to the Python icon -> Extension settings)
in the search bar type #ext:ms-python.python venv
in the User settings in section "Python: Venv Path" enter the directory where all your virtual environments lie (= $WORKON_HOME)
After that I restarted VSCode and it didn't complain anymore in the launch.json file (or in my case, the .code-workspace file), VSCode immediately found the python interpreter in the virtual environment and everything worked fine again.

How do you debug a Linux core dump using VSCode?

I am purposely generating a core dump from a C++ application I'm writing using VSCode. I cannot figure out how to debug the core dump. Has anyone had any experience with this they'd be willing to share?
***** UPDATE *****
I believe I have it working now. I created a second debug configuration for core files. I needed to add the "coreDumpPath" option that pointed to the dump file generated. I also needed to remove preLaunchTask option that would always build a new executable.
From the VScode docs
Memory dump debugging
The C/C++ extension for VS Code also has the ability to debug memory dumps. To debug a memory dump, open your launch.json file and add the coreDumpPath (for GDB or LLDB) or dumpPath (for the Visual Studio Windows Debugger) property to the C++ Launch configuration, set its value to be a string containing the path to the memory dump. This will even work for x86 programs being debugged on an x64 machine.
P.S.
The asker has already updated the question with the solution. But adding this answer to help those people who jump directly into the answer section ;)
Update:
Sample launch.json for C/C++ extension without hardcoding core file name
{
"version": "0.2.0",
"configurations": [
{
"type": "cppdbg",
"request": "launch",
"name": "Open a core dump(c/c++)",
"program": "<Path to the program here>",
"coreDumpPath": "${input:coreFileName}",
"cwd": "${workspaceFolder}",
"MIMode": "lldb" // or gdb, if you are using gdb
}
],
"inputs": [
{
"id": "coreFileName",
"type": "promptString",
"description": "Enter core file path"
}
]
}
Sample launch.json for CodeLLDB extension without hardcoding core file name
{
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "custom",
"name": "Open a core dump",
"initCommands": [
"target create -c ${input:coreFileName}"
]
}
],
"inputs": [
{
"id": "coreFileName",
"type": "promptString",
"description": "Enter core file path"
}
]
}
To give a concrete example of #insaf's answer. This can be used as a template for launch.json (click the settings button on top of the debug side-bar to edit it):
{
// 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": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "<PATH-TO-BINARY>",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"coreDumpPath": "<PATH-TO-CORE-DUMP>"
}
]
}
Edit the paths of the binary and core dump accordingly.
Then press the green play button (start debugging) -- it doesn't really start anything but load the core dump.
I wrote a little helper script that duplicates the functionality of coredumpctl in a machine-readable way.
It
searches the systemd journal for logged coredumps
uses fzf to allow the user to interactively select one of them
decompresses the selected coredump to /tmp/coredump
links the associated executable to /tmp/coredump_program
Then I created the following tasks.json:
{
"version": "2.0.0",
"tasks": [
{
"label": "select coredump",
"type": "shell",
"command": "coredumpselect.py",
"args": [],
"presentation": {
"reveal": "always",
"panel": "new"
}
}
]
}
and added the following debug configuration to launch.json:
{
"name": "View coredump",
"type": "cppdbg",
"request": "launch",
"program": "/tmp/coredump-program",
"args": [],
"cwd": "${workspaceRoot}",
"coreDumpPath": "/tmp/coredump",
"preLaunchTask": "select coredump",
"MIMode": "gdb",
}
Now when you launch the "View coredump" debugging action, you'll be given an interactive choice of coredumps in the terminal. After selecting one of them, the vscode debugger will open it.
To run the script on your Linux system, you need to install the systemd Python package. On Ubuntu, use sudo apt install python3-systemd. On Arch Linux, use sudo pacman -S python-systemd. With pip, the packages is available as systemd-python (not to be confused with systemd, which is a different incompatible package). You'll also need fzf (sudo apt install fzf, sudo pacman -S fzf), and the proper decompressor for the coredump (e.g. lz4 or zstd).
I defer to the two examples above for launch.json configurations but in addition to that, if you have any home grown .so libraries, you're going to want to add
"additionalSOLibSearchPath": "${workspaceFolder}/path/to/sharedobjects/",
or it won't find the symbols for those libraries which in my case were terribly important.
You don't use a source code editor (even VSCode) to debug a core dump (because a core file has not a textual format). You use gdb (or perhaps some other debugger, such as lldb). GDB has a very nice user manual that I strongly recommend to read. You also don't use VSCode to compile your C++ code, but a compiler such as GCC or Clang (probably VSCode could be configured to start g++ for you).
On Linux, if your C or C++ program was built with -g passed to g++ or gcc as an executable $HOME/bin/foo you could try
gdb $HOME/bin/foo core
then use post mortem commands of the gdb debugger. Read the documentation of gdb for details. The presence and name of the core dump file is configurable (at the lowest level using setrlimit(2) and thru proc(5), so bash builtin ulimit or zsh builtin limit). See also core(5). Notice that your login shell could be changed with chsh(1). On Linux, bash is often (not always) the default shell, but you might switch to zsh or even to the fish shell. Read of course about Unix shells.
You also don't need to generate a core dump on purpose. It is often simpler to set a breakpoint under gdb. You could generate a core of a running process using gcore(1). You could attach gdb to a running process using the -p option of gdb(1). I see very few cases where generating a core dump on purpose is useful. But of course abort(3) (also used by assert(3)) generates a core dump.
Your application should better be compiled (using the -g option to GCC or Clang) with DWARF debug information. Assume your application executable is some yourapp executable file. Then you debug the core dump (for a core file, see core(5) for more; notice that gdb(1) is mentioned in core(5) man page, given by the man core command) using gdb yourapp core
Some source code editors are capable of running gdb (my editor is emacs and it is capable of running gdb with M-x gdb). You should dive into the documentation of your source code editor to understand how to do that.
But I recommend using gdb on the command line in a terminal. It is a very handy tool. See this answer to a related question.
gdb is using the very low level ptrace(2) system call to set breakpoints etc etc.. You almost never need ptrace (except if you write your own debugger, which could take years of work), but you use gdb which uses ptrace.
PS. How to run gdb from VSCode is a different question. Since I don't use VSCode, I cannot answer it. And it might not even worth doing. Even with 30 years of emacs experience, I often run gdb in a terminal. Since it is simpler than running it from emacs (or VSCode).
NB. These days, in 2019, "source code editor" is a near synonym for "IDE". Both locutions in practice refer to the same products, but they differ in the way they present them. You can call emacs an IDE, I (and the GNU community) prefer to call it a source code editor, but we both will use it for the same things: nicely writing and browsing and working on source code and building and debugging it.

Resources