Search code examples
pythonenvironment-variablesvisual-studio-codevirtual-environment

vscode/Python | unable to acess environment variables


So basically my issue is that I have no idea why I can't access the environment variables that I have set in my .env file. I'm pretty sure I have set it up correctly because AERPL produces the correct output, but when I use my terminal (Git-bash) or code runner, they can't access the environment variables and just spit out an error. I have done a lot of searching online, but for the life of me I can't figure out why it isn't working. I'm sure there is some easy fix that I am somehow missing... But if anyone can figure out why it isn't working, please let me know. Thank you in advance!


File Structure

cwd/
    .vscode/
        settings.json
    env/
        Lib/
        Scripts/
        .env
    testenv.py

settings.json

{
    "python.testing.promptToConfigure": false,
    "python.testing.pytestEnabled": false,
    "python.testing.unittestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.pythonPath": "${workspaceFolder}\\env\\Scripts\\python.exe", // Python 3.8.2
    "python.envFile": "${workspaceFolder}\\env\\.env",
    "python.formatting.provider": "autopep8",
    "editor.formatOnSave": true,
    "python.linting.enabled": true,
    "code-runner.executorMap": {
        "python": "$pythonPath -u $fullFileName"
    },
    "code-runner.clearPreviousOutput": true,
    "code-runner.showExecutionMessage": true
} 

.env

TEST = "test"

testenv.py

import os
print(os.getenv('TEST'))
print("==========")
print(os.environ['TEST'])

Code Runner/Integrated Terminal Output:

os.getenv: None
==========
Traceback (most recent call last):
  File "c:\test\testenv.py", line 4, in <module>
    print(f"os.environ: {os.environ['TEST']}")
  File "c:\python38\lib\os.py", line 675, in __getitem__
    raise KeyError(key) from None
KeyError: 'TEST'

$ py testenv.py
os.getenv: None
==========
Traceback (most recent call last):
  File "testenv.py", line 4, in <module>
    print(f"os.environ: {os.environ['TEST']}")
  File "c:\python38\lib\os.py", line 675, in __getitem__
    raise KeyError(key) from None
KeyError: 'TEST'

AEREPL Output

Print Output:
os.getenv: test
==========
os.environ: test
Variables:
{}

Solution

  • You may force to recognize environment varibles in integrated terminal by VSCode without entering to debug mode. This example is for Linux and bash.

    • Find parameter terminal.integrated.profiles.linux
    • Add to settings.json, correct paths to actual .env file and shell:
            "bash-env": {
                "path": "bash",
                "icon": "terminal-bash",
                "args": ["-c", "if [ -f .env ]; then export $(cat .env); fi; if [ -f .vscode/.env ]; then export $(cat .vscode/.env); fi; bash"]
            },
    
    • Find parameter terminal.integrated.defaultProfile.linux
    • Choose profile bash-env

    This example is inspired by issue