Python: Cannot debug using vs code using virtual environment - python

I set up a python virtual environment named "myenv" in my project. Then, I try to debug the script from VS code.
Here is the output. Please give some insights. Thanks
$ cd d:\\xx\\yy ; env PYTHONIOENCODING=UTF-8 PYTHONUNBUFFERED=1 d:\\xx\\yy\\myenv\\Scripts\\python.exe c:\\Users\\xyz\\.v
scode\\extensions\\ms-python.python-2019.6.24221\\pythonFiles\\ptvsd_launcher.py --default --client --host localhost --port 1817 d:\\xx\
\yy\\.vscode\\launch.json
bash: env: command not found
(myenv)
My launch json looks like below.
{
// 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"
}
]
}

If you install and use Python Extension from Microsoft then you can just start VS Code from your project root folder: code . Then open some Python source file and in the lower left corner at the bottom status bar of VS Code you will see your current Python execution environment. You can click and change it by selecting your environment from the list.

I think the problem is you are running under Windows but you set your shell to bash. If you're using WSL then please see the instructions on remote development which includes WSL. If you're using git-bash then please note the Python extension does not support git-bash as a shell.

Related

Executing Python code in VScode outputs Python PATH and project's absolute path to console

When I execute a simple print('Hello world') by using "Run Python File" in VScode I get this output
barakiva#pop-os:~/Development/Educational/Languages/Python/lang$ /usr/bin/python3
/home/barakiva/Development/Educational/Languages/Python/lang/vars.py Hello world
However, opening VScode's integrated console and typing python3 vars.py outputs normally with no clutter
barakiva#pop-os:~/Development/Educational/Languages/Python/lang$ python3 vars.py
Hello world
This happens because the code is run through the Terminal.
In short, under the hood, VSCode opens a new terminal and executes the command to run your program using the full path. It's done this way to avoid possible conflicts, if you choose to e.g. use an external terminal with a custom configuration.
VSCode can also display the program output only, via the Debug Console (tab to the left from Terminal). To do this, you need to create a custom launch configuration.
In the Run and Debug tab click create a launch.json file (if you don't have one already) and select the Python File template. Then, in .vscode/launch.json change property "console": "integratedTerminal", to "console": "internalConsole" for the desired configuration. See the complete config below:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "internalConsole",
"justMyCode": true
}
]
}
With this in place, you can run your Python file like before, and see the program output in the Debug Console:

Exception has occurred: ImportError Vscode While Debugging

I am trying to try the debug tool in my vs code I am totally new to vs code and I am getting an error such as this when I run it
ERROR MESSAGE I have a folder called .vscode with a launch.json file `
"version": "0.2.0",
"configurations": [
{
"name": "Python: Django",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}\\myPro\\manage.py",
"args": [
"runserver"
],
"django": true,
"justMyCode": true
}
]
}
I watched a lot of videos on youtube and I see people who have settings.json in there .vscode file.
WHAT I HAVE DONE:
I have downloaded django == 3.25
I have downloaded python == 3.10.4
IN a virtual environment my environment works perfectly fine its just that I can find the reason to this problem I would really appreciate it if someone can help me out
Try Ctrl + Shift + P and the option "Select Python Interpreter", then select the one in which the environment is. This should have VSCode running in the same environment.
Please change your debug settings to your Virtual Environment
Open .py file and then debug it.
You may have to restart vscode

Debugging dockerized Django in VS Code results in error "Timed out waiting for launcher to connect"

I want to debug my Django application using a docker container in Visual Studio Code.
Microsoft published a guide how to do that, which I followed step by step:
https://code.visualstudio.com/docs/containers/quickstart-python
But when I try to run the debugger, I get the following error message:
Timed out waiting for launcher to connect
Here is what I did step by step:
I initialized a simple Django application using django-admin startproject helloworld
In VS Code I opened the folder including the manage.py
Opened Command Palette Ctrl + Shift + P, and then selected Docker: Add Docker Files to Workspace...
Select Application Platform Python: Django
Include Docker Compose files No
Relative path to the app's entrypoint manage.py
What ports does your app listen on? 8000
VS Codes then creates several files (see below).
When I try to start the debugger (like in the guide), I get the following error message:
The terminal doesn't show any error messages, but the commands executed:
.vscode/launch.json:
{
"configurations": [
{
"name": "Docker: Python - Django",
"type": "docker",
"request": "launch",
"preLaunchTask": "docker-run: debug",
"python": {
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "/app"
}
],
"projectType": "django"
}
}
]
}
.vscode/tasks.json:
{
"version": "2.0.0",
"tasks": [
{
"type": "docker-build",
"label": "docker-build",
"platform": "python",
"dockerBuild": {
"tag": "dockerdebugging:latest",
"dockerfile": "${workspaceFolder}/Dockerfile",
"context": "${workspaceFolder}",
"pull": true
}
},
{
"type": "docker-run",
"label": "docker-run: debug",
"dependsOn": [
"docker-build"
],
"python": {
"args": [
"runserver",
"0.0.0.0:8000",
"--nothreading",
"--noreload"
],
"file": "manage.py"
}
}
]
}
Dockerfile:
# For more information, please refer to https://aka.ms/vscode-docker-python
FROM python:3.8-slim-buster
EXPOSE 8000
# Keeps Python from generating .pyc files in the container
ENV PYTHONDONTWRITEBYTECODE 1
# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED 1
# Install pip requirements
ADD requirements.txt .
RUN python -m pip install -r requirements.txt
WORKDIR /app
ADD . /app
# Switching to a non-root user, please refer to https://aka.ms/vscode-docker-python-user-rights
RUN useradd appuser && chown -R appuser /app
USER appuser
# During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "helloworld.wsgi"]
requirements.txt:
# To ensure app dependencies are ported from your virtual environment/host machine into your container, run 'pip freeze > requirements.txt' in the terminal to overwrite this file
django==3.0.3
gunicorn==20.0.4
VS Code Version: 1.47.1
Python Extension Version: v2020.7.94776
The idea of debugging in vs code is to:
use debugpy to launch your code with a port, say 5678
in vscode to 'Remote Attach' to that process.
I may be wrong but what i can see from your code, you didn't attach to your process.
I wrote the way I did here, I use docker-compose and docker. My way is different with yours but you will get the idea...:)
My issue were missing packages. Docker usually works fine, I haven't had any issues before at all.
I originally installed docker like described in the official documentation:
https://docs.docker.com/engine/install/ubuntu/
But after I tried installing the docker.io package, debugging worked fine in VS Code:
sudo apt install docker.io
There's no errors compared to the vscode tutorial in your project. Cause the error is timeout waiting for luncher to connect, try restart docker service and reload your window in vscode.
Here is a clue and a workaround:
The instructions I followed had me open VS code inside my ubuntu WLS2 instance. Note: my app is just a generic python app, not django.
If I click this and change it to open as a windows folder, then fun debug, everything suddenly works for me. (It spins up the docker and connects to it with debug, does breakpoints etc.)
I think what is happening for me is that "sometimes" docker is starting the container/app on its own WSL instance and my ubuntu instance cannot route to it for the debug.
I say sometimes, because sometimes it works. I think it might be related to which application (docker, ubuntu, vscode) I start first when I boot my machine.
I've messed with the docker, resources, WSL integration settings, the windows firewall, and restarted various things.
I'm sure a proper fix is not that complicated, however running VS code in native windows is enough of a fix for me. I don't see why the added complexity of starting the VS code session inside WSL is actually necessary.

how to add optirun to vscode debug options?

I use manjaro and want to use vscode tool for debug my python program,but i use CUDA, so i usually use a command like this:
optirun ipython program.py arg1 arg2
when i try to debug the program optirun isn't called, so i don't have access to GPU, how can i call optirun before python (or ipython)?
I've tried to change settins.json and launch.json to add it to command but it doesn't work.
Thanks.
This is what I did and it worked.
Make a bash script, name it anything, assume script.sh.
#!/bin/bash
optirun python "$#"
In .vscode/launch.json set "pythonPath" to ./script.sh.
Here is a example 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: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"linux": {
"pythonPath": "./script.sh"
},
}
]
}
Now it should work as intended.
I also faced the same problem while debugging a OpenCL application in python. My Nvidia graphics card was managed by optirun. $# passes all the command line arguments supplied by vscode to the python interpreter.
You could try editing your launch.json to point to optirun as your Python interpreter via the "python.pythonPath" setting.

Setting environment variables for integrated terminal

I am seeking help figuring out how to setup environment variables for integrated terminal within Visual Studio Code. Currently I am able to do so with .env file inside my workspace folder, but I'd like to change the filename for this file and create another one or two, let's say dev.env and prod.env. Setting "python.envFile" for my workspace doesn't do the trick and from what I understand changing things in launch.json is for debugging.
The overall goal of all this (and that is important) is to run flask shell (integrated shell for flask web framework, python) with a certain set of env variables and be able to change them by swapping files. I know I could set these by introducing "terminal.integrated.env.osx" to my workspace settings, but I'd rather get these variables from a file.
Thanks a lot for your time and help.
UPD >>
I guess one way to go about it would be to create two tasks as such:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "FLASK SHELL DEV",
"type": "shell",
"command": "source ${workspaceFolder}/dev.env && ${config:python.pythonPath} -m flask shell",
"problemMatcher": []
},
{
"label": "FLASK SHELL PROD",
"type": "shell",
"command": "source ${workspaceFolder}/prod.env && ${config:python.pythonPath} -m flask shell",
"problemMatcher": []
}
]
}
but the question stands. Is there a way to do the same with integrated terminal?
Yes, you can use one of these settings (depending in your platform):
"terminal.integrated.env.linux": {},
"terminal.integrated.env.windows": {},
"terminal.integrated.env.osx": {
"PYTHONPATH": "${workspaceFolder}/src:${env:PYTHONPATH}"
},
However, they will only work for the integrated terminal, not for any other processes the vs code python extension might spawn (tests, linting, debugger). For those you need to use the .env file.
Edit:
It is worth noting that if you start VS Code from the terminal it should inherit any env variables from terminal environment (at least for all the spawned subprocesses, probably not for the integrated terminal).
If you don't want to set environment variables using the terminal you can do it using configuration files.

Categories