Setting environment variables for integrated terminal - python

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.

Related

Attach a debugger to Azure Function App running in a container

I am curious to know if anyone successfully attached a debugger to a python script -
which is actually an Azure Function App running in a container.
I have all the VSCODE extensions but still can't seem to connect to the running container.
I've run the container from docker-compose.debug and from Bash cmd:
$ docker run -p 5678:5678 -it -e AzureWebJobsStorage="UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://host.docker.internal" nfunc:latest
NB I have to set an environment variable AzureWebJobsStorage for the storage.
My launch.json as follows:
{
"name": "Python: Remote Attach",
"type": "python",
"request": "attach",
"connect": {
"host": "0.0.0.0",
"port": 5678
},
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "."
}
]
},
What am I missing please ..
Can Functions Apps be debugged at all in a container?
Why does it not hit a breakpoint ?
Thank you
In this case, I believe you'll have to do the profiling. You will have to follow these:
If its not a blessed image, then first you would have to install SSH
if you want to get into the container.
Then you will have to make use of tools such as cProfile or other related python modules to profile the code.
Here is a documentation for windows application. You might want to take a look :
https://azureossd.github.io/2017/09/01/profile-python-applications-in-azure-app-services/index.html
This issue has been tracked : https://github.com/Azure/azure-functions-docker/issues/17

Separate .env for testing vs debug

I'm utilizing VSCode devcontainers, and I'm having difficulty trying to figure out how to run a different .env file for my pytest setup, versus when I just want to run uvicorn/debug.
I can set an envfile in settings.json, which works, but I'd have to change this path back and forth depending on whether I wanted to test or just run the server. I've read that you can change the envfile for tests in launch.json, but when discovering/running tests in no longer appears these are valid settings for launch.json, and must be baked into the vscode-python extension?
I'm really confused because I feel like this is a common use case, all I am really trying to accomplish is setting a different DB connector so that test can drop/create tables for tests, but dev would persist in a separate database.
For anyone who stumbles upon this, I found a workaround which is to specify a certain envfile for running and debugging, and then use a separate env in settings.json which will apply for the tests.
So Imagine you have
dev.env which contains
environment=dev
...
and test.env which contains
environment=test
...
Then you would include this line in your .vscode/settings.json
"python.envFile": "${workspaceFolder}/test.env"
and this is what my launch configuration looks like for bringing up fastapi with uvicorn:
{
"name": "Python: FastAPI",
"type": "python",
"request": "launch",
"module": "uvicorn",
"envFile": "${workspaceFolder}/dev.env",
"args": [
"app.main:app",
"--reload"
]
}
It's a little odd that this is how it has to be configured, but it seems to work for now.

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 use the vscode python debugger with a project built with bazel?

I want to debug a python file which has a few dependencies that only appear in the runfiles from bazel. How can I debug a bazel build with the vscode debugger?
As someone famous said, "Yes, we can".
You would need to use the "ptvsd" python package.
One-time Setup
Add "ptvsd" as a Python dependency in Bazel
In VS Code, in your launch.json file, add the following configuration:
{
"name": "Python: Attach",
"type": "python",
"request": "attach",
"port": 5724,
"host": "localhost"
},
Debug
When you want to debug a specific file:
In the Python file you want to debug, add the following lines:
import ptvsd
ptvsd.enable_attach(address=('localhost', 5724), redirect_output=True)
print('Now is a good time to attach your debugger: Run: Python: Attach')
ptvsd.wait_for_attach()
Run Bazel on this file as you normally would (bazel run :server for instance)
Execution will stop at "Now is a good time to attach your debugger: Run: Python: Attach"
In VS Code, click on the "Python: Attach" debug option that we setup earlier:
That's it!
Feel free to change the port, 5724 in this example.
ptvsd is deprecated, replaced by debugpy.
Usage is the same as the accepted answer, except that the code snippet for the Python file has changed:
import debugpy
debugpy.listen(5678)
debugpy.wait_for_client() # blocks execution until client is attached

Python: Cannot debug using vs code using virtual environment

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.

Categories