Running Python3 script in VS Code doesn't recognize environment variables unless running debugger (MacOS)
Asked Answered
D

0

7

To clarify I set up the .env file for environment variables correctly and when I run the code either via the built-in terminal (default play button) or to output via the Code Runner plugin, the attempts to grab those environment variables always end up null. However, the same thing works when running via debugger with no problem.

This has been a relatively widely experienced issue ~3 years ago from my research. I followed the official documentation exactly and I know I formatted the .env file right because it works with the debugger.

I checked all posts I found across StackOverflow and the VS-Code GitHub trying dozens of solutions. A lot of these mentioned solutions didn't work for me or are out of date for Monterey. I've tried several things from these and on my own including:

  • Disable Code Runner
  • Rename file to dev.env and others, while reflecting Env File path in VS Code settings
  • Placing .env file in vscode and .venv folders while reflecting in path
  • I've tried a series of commands in the settings JSON I've found online. Sorry, I'm not going to be more specific, I've tried so many.
  • I haven't tried installing environment variables to the python path yet, something I'm unclear on how to do if it makes sense to do so.

I'm using the last-gen of Intel Mac running the latest macOS Monterey 12.3.1, the latest VS Code 1.66.2, and the latest version of Python 3.10.4. Currently, I have the default Env File path set: ${workspaceFolder}/.env and a file named .env in the workspace folder.

Unless I'm missing something I'm not sure how this would have gone unresolved for this long and/or I'm missing the solution. Regardless of what I've tried, I'd like to know what the best/go-to solution is for almost everyone faced with this problem. Thank you for your help.

Diachronic answered 20/4, 2022 at 18:23 Comment(5)
Could you add some code relevant to the env variable calling (how do you get the variables with python)? In a way that is minimal and reproducibleWilk
Hey @FreddyMcloughlan, thanks for the response. I am using import os and os.getenv('ENVVAR'). the file name is .env and the file syntax is ENVAR=VALUE (no spaces or quotation marks).Diachronic
Have you tried os.getenvb(b"ENVAR")Wilk
I have not tried that before. I did just now try that exactly and I still only retrieve None. Thanks for the suggestion! I'm almost positive this issue isn't going to be solved by Python, rather VS Code settings and the way files are structured. Like you know, it works in the debugger and os.getenv works when I run this on server, in terminal, etc. If it helps, when I run in terminal I have to do the following to have the .env file recognized: set -a source .env set +a (in that order, three separate commands)Diachronic
Ever found a solution? Running into the same issue.Legionary

© 2022 - 2025 — McMap. All rights reserved.