Search code examples
pythonvisual-studio-codeenvironment-variablesdotenv

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


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

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"))

Solution

  • 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?

    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

    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...