Why I can't access my environment variable from .env file in vscode python?

Question:

I am really new to the space so sorry if my questioning is bad or I ask novice questions. also thanks in advance for the repliers!

what I am trying to do?
I am trying to access my environment variable from the .env file and print its value in the terminal.

What is the issue?
When I run the script in the terminal I keep getting the error none

I checked a few forums and the dotenv paper about the issue but none helped me solve this

some more info:

I am using windows 10

The version of dotenv is 0.20.0

I downloaded it using python -m pip install python-dotenv

the code

.env file –
export PRIVATE_KEY = 0xc3c4e4fe27d8e6b06710e713878e4488c034ce346a578fdfa78bb3d335130eec

the python file –

from dotenv import load_dotenv

 import os

 load_dotenv()

 print(os.getenv("PRIVATE_KEY"))










Asked By: boten500

||

Answers:

You can set the envfile node in the launch.json file, point to your .env file (using an absolute path),.

Then press F5 to debug the code, or click the green triangle button after selecting the Run and Debug icon on the left.

enter image description here

Below is a sample of my code along with the output.

Project structure:

enter image description here

launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "envFile": "C:\WorkSpace\pyenv\py.env",

            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "justMyCode": true
        }
    ]
}

py.env:

PRIVATE_KEY = 123456789abcdefghijklmn

Test.py:

import os

print(os.getenv("PRIVATE_KEY"))

terminal output:

enter image description here

update:

dotenv gets the environment variables in the .env file by default.
If you change the py.env file name in your project to .env. then the code you showed in your question will run successfully without any changes.

enter image description here

Answered By: JialeDu

first thanks for the replies! Didn’t expect an answer in less than a 24h, it really feels nice.

So I solved my issue but it wasn’t after removing the "export" in the .env file (I tried with and without it both gave the same results in the terminal), I had to specify the full path of the .env file in the load_dotenv(), apparently I had to specify it but many code samples I saw in forums didn’t need to do it I wonder why…

anyway here is the new code…

the python code –

enter image description here

the .env file –

enter image description here

by the way it’s not a real private key

I am not gonna close this thread yet, I still have a question regarding this issue as it was more luck that helped me solve this…I don’t want to see this issue pop up again for me in the future so if anyone can answer my question it would be great!

At some point before I found the solution I ran the python script in the terminal and got a random private key (I don’t have it pictured sadly), it might had been a key I set in the past but then I checked if I had other .env files in the folder but I had none I also didn’t have any environment variables in System Properties > Advanced > Environment Variables on windows so where does dotenv gets the key values by dafault? also After that I reopened vscode and tried again but I got a none error…

Answered By: boten500

If all the solutions don’t work, and your .env file still won’t work, here is a workaround:

Add the following lines to the top of your main routine (or to conftest.py if you need them for tests).

This code will read your .env file and create your environment variables:

# Workaround for .env file not working
temp_res = os.getenv("SOME_VARIABLE", "") # Try to read an env variable
if temp_res == "": # Nope, .env file settings are not present
    # Manually load environment variables
    with open(os.path.expanduser("~/path/on/my/laptop/my_env_file.env")) as env_file:
        for line in env_file:
            lhs = line.split("=")[0]
            rhs = line.split("=")[1]
            os.environ[lhs]=rhs.strip()
Answered By: CyclingDave

(I posted the same answer here: https://stackoverflow.com/a/77337086/12087525)

I’ve came across this same issue today.
Once I undestood that the problem was related to the root directory the dubugger was set, it was straight forward to fix it:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "cwd": "${fileDirname}", // <- the secret is here
            "console": "integratedTerminal",
            "justMyCode": true
        }
    ]
}

Just add "cwd" as the ${fileDirName} so you set the root directory as the file directory itself, then all the relative paths are going to be fixed as well.

Rederences:

Answered By: guilfer