I have a simple python app with this file directory:
C:.
├───Sample Project
│ ├───project
│ │ ├───.vscode
│ │ ├───bin
│ │ ├───models
│ │ ├───projects
│ │ │ └───test
│ │ └───utils
│ └───venv
Inside C:\Users\usr\Desktop\raicom\Sample Project\project
is my project.env
which contains:
sample=hello
sample2=world
Inside C:\Users\usr\Desktop\raicom\Sample Project\project\.vscode
is my settings.json
which contains:
{
"python.envFile": "${workspaceFolder}/project.env"
}
Inside C:\Users\usr\Desktop\raicom\Sample Project\project\projects\test
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.
but when I click Run Python File, it outputs None on both cases:
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?
CodePudding user response:
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.
CodePudding user response:
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