Problem with getting an environmental variable through os.getenv()

Viewed 269

I'm trying to code a discord bot, so, to avoid showing the token directly in the code, I'm going for an environmental variable.

In my TOKEN.env file, I wrote TOKEN=*token*, and this is my code, but Python won't get the variable.

import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('TOKEN')

bot = commands.Bot(command_prefix='$')
bot.run(TOKEN)

I'm using pycharm and Python 3.9

2 Answers

Since you are saving your environment variables in TOKEN.env, you need to tell dotenv to use this file:

from dotenv import load_dotenv

load_dotenv('path/to/file/TOKEN.env')

Option #1: Default path

Save the config in a file called .env.

Then, use this code in your application:

from dotenv import load_dotenv

load_dotenv()

Option #2: Use a custom path

Just load from any path:

from dotenv import load_dotenv

load_dotenv('path/to/file/TOKEN.env')

Option #3: Set the environment variable while running the app

You don't need to do anything from inside your Python code except for calling os.getenv.

You do however need to run your application while specifying the value:

>> TOKEN=*token* python3 script.py
- OR -
>> TOKEN=*token* ./script.py
Related