Andrea Colombo
Andrea Colombo

Reputation: 21

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

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

Upvotes: 2

Views: 2334

Answers (2)

Daniel Trugman
Daniel Trugman

Reputation: 8491

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

Upvotes: 2

Philip Ciunkiewicz
Philip Ciunkiewicz

Reputation: 2791

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

Upvotes: 4

Related Questions