2

I know the module os and how to use like os.environ.get('a', 'b'). It will catch current environment variable 'a', if not exists will default to 'b'.

But today I have a small problem. This is my tiny project about the problem:

.vscode/
    launch.json
.env
runme.py

For runme.py:

import os

vv = os.environ.get('SETTINGS', 'Nothing')

print(vv)

And also the .env file is quite simple like runme.py

SETTINGS = proj.settings.local

In launch.json, follow Python debugging configurations in VS Code

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/runme.py"
        }
    ]
}

After that, press F5, I see what I expect to see in INTERNAL TERMINAL

>cd d:\tmp\tt && cmd /C "set "SETTINGS=proj.settings.local" && set "PYTHONIOENCODING=UTF-8" && set "PYTHONUNBUFFERED=1" && python c:\Users\tony\.vscode\extensions\ms-python.python-2018.7.1\pythonFiles\PythonTools\visualstudio_py_launcher.py d:\tmp\tt 62502 34806ad9-833a-4524-8cd6-18ca4aa74f14 RedirectOutput,RedirectOutput D:\tmp\tt/runme.py " 
proj.settings.local

But when I just run the command in COMMAND LINE python runme.py, I saw 'Nothing' printed in COMMAND LINE. WHY?

Is that IDE(ex: VSCode) do for me? Or something I misunderstand about the os module? Please explain it to me.

Tony Chou
  • 584
  • 1
  • 9
  • 26

1 Answers1

1

This seems to be a problem with VS Code. It seems that the way the .env file is evaluated and applied to a terminal is not very consistent and predictable.

During my test, the .env file only gets picked up, if you use the Debug function (shortcut F5 or Ctrl+F5). This results in the content of .env getting injected into the terminal session. Until you close that terminal, the variables you have defined there will be available for any consecutive runs of your program(s), if started from that terminal. Any new terminal you open (even if it is a new terminal inside VS Code) will not have access to these variables.

If you want an environment variable available at all times in a terminal, you can set that environment variable on the OS level. Under Windows, use System Properties / Environment Variables... and put it under User variables or System variables, depending on your needs. Under Linux, put it in your shells .rc file. Please note that you have to restart VS Code for the change to take effect.

Cryn
  • 1,005
  • 1
  • 9
  • 13