VS Code is showing the inline comments and quotes from my .env file when importing environment variables and I can't figure out why. It does not happen if I run the script from terminal, only within VS Code -> Run. Also
dotenv is quite forgiving per the docs:
Values can be unquoted, single- or double-quoted. Spaces before and after keys, equal signs, and values are ignored. Values can be followed by a comment.
Here's my .env:
TEST='abc'
TEST2="def"
TEST3='ghi' # comment 1
TEST4="hig" # comment 2
Here's the file test_dotenv.py:
import os
from dotenv import load_dotenv
load_dotenv()
print("-=-START")
print(os.getenv('TEST'))
print(os.getenv('TEST2'))
print(os.getenv('TEST3'))
print(os.getenv('TEST4'))
In terminal, it runs as expected:
python ./tests/component/test_dotenv.py
-=-START
abc
def
ghi
hig
In VS Code, it doesn't:
-=-START
abc
def
'ghi' # comment 1
"hig" # comment 2
This seems to be a known issue. VS Code's Python extension does some dotenv parsing stuff on its own (but doesn't seem to always handle inline comments after values properly) and the actual dotenv (which does support inline comments after values- see the "File Format" section of the docs) will not override existing evironment variables. See issue ticket pythonTerminalEnvVarActivation should reproduce python-dotenv comments behaviour #23012 (which is now being tracked by Standardize how to do environment variable parsing & substitution #18307).