skip to Main Content

I have a simple python app with this file directory:

C:.
├───Sample Project
│   ├───project
│   │   ├───.vscode
│   │   ├───bin
│   │   ├───models
│   │   ├───projects
│   │   │   └───test
│   │   └───utils
│   └───venv

Inside C:UsersusrDesktopraicomSample Projectproject is my project.env which contains:

sample=hello
sample2=world

Inside C:UsersusrDesktopraicomSample Projectproject.vscode is my settings.json which contains:

{
    "python.envFile": "${workspaceFolder}/project.env"
}

Inside C:UsersusrDesktopraicomSample Projectprojectprojectstest is a file named test.py which contains:

import os

print(os.environ.get('sample'))
print(os.environ.get('sample2'))

this should print my environment variables. When I run debug mode, it does just that.

enter image description here

but when I click Run Python File, it outputs None on both cases:

enter image description here

What could I be missing or doing wrong?

Follow up question, why is it working in debug mode but not in the run python file mode?

2

Answers


  1. It works in debug mode because when you run it from debug mode the Current working directory is the project root directory, but when you right click and say run python file in terminal it runs it with the current working directory as the directory containing the python script.

    When it is run with the current working directory as the python script directory it doesn’t take into account your .vscode settings.

    A solution is to use a module to load your .env file for example: python-dotenv

    Login or Signup to reply.
  2. Please use debug mode.

    Environment variable definitions files can be used for scenarios such as debugging and tool execution (including linters, formatters, IntelliSense, and testing tools), but aren’t applied to the terminal.

    Read docs for more details.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search