Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment Variable not loading with load_dotenv() in Linux

I'm trying to make a discord bot, and when I try to load a .env with load_dotenv() it doesn't work because it says

Traceback (most recent call last):
  File "/home/fanjin/Documents/Python Projects/Discord Bot/bot.py", line 15, in <module>
    client.run(TOKEN)
  File "/home/fanjin/.local/lib/python3.8/site-packages/discord/client.py", line 708, in run
    return future.result()
  File "/home/fanjin/.local/lib/python3.8/site-packages/discord/client.py", line 687, in runner
    await self.start(*args, **kwargs)
  File "/home/fanjin/.local/lib/python3.8/site-packages/discord/client.py", line 650, in start
    await self.login(*args, bot=bot)
  File "/home/fanjin/.local/lib/python3.8/site-packages/discord/client.py", line 499, in login
    await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip

Here's my code for the bot:

import os

import discord
from dotenv import load_dotenv

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

client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')

client.run(TOKEN)

And the save.env file: (It's a fake token)

# .env
DISCORD_TOKEN={XXXXXXXX}

Both files are in the same directory, and I even tried to explicitly specify the .env's path with

env_path = Path('path/to/file') / '.env'
load_dotenv(dotenv_path=env_path)

but that also didn't work

like image 817
F.M Avatar asked Nov 30 '25 10:11

F.M


1 Answers

I had a similar issue, and in my case, this solved it:

Instead of doing load_dotenv() I needed to do load_dotenv(override=True). This was because I had set one of the variables from the .env file manually, and so it was not updating with the value set in the .env file.

The parameter override defaults to False. Here is the definition, taken from the dotenv github:

override: Whether to override the system environment variables with the variables
            from the `.env` file.
like image 193
breadmaker Avatar answered Dec 03 '25 03:12

breadmaker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!