如何让我的 .env 文件在我的 .py 文件中工作?
How would I make my .env file work in my .py file?
制作一个不和谐的机器人,我想将变量存储在 .env
文件中。
它抛出这个异常:
File "c:\Users\Adam\Documents\DiscordBot\main.py", line 24, in <module>
client.run(TOKEN)
File "C:\Users\Adam\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\Adam\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\Adam\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 665, in start
await self.login(*args, bot=bot)
File "C:\Users\Adam\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip'
在我将变量移动到 .env
文件之前它工作正常。
#.py
import os
from dotenv import load_dotenv
import discord
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
GUILD = os.getenv("GUILD_NAME")
client = discord.Client()
@client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f"{client.user} is connected to the following guild:\n"
f"{guild.name}(id: {guild.id}"
)
client.run(TOKEN)
#.env
DISCORD_TOKEN=my_discord_token
GUILD_NAME=Testing
我的 .env
和 .py
在同一个文件夹中。
python-dotenv
的 load_env()
在与执行它的目录相同的目录中搜索 .env
文件。
如果您将 .env
文件名更改为自定义文件名,例如 var.env
,您必须指定文件名:load_env("var.env")
制作一个不和谐的机器人,我想将变量存储在 .env
文件中。
它抛出这个异常:
File "c:\Users\Adam\Documents\DiscordBot\main.py", line 24, in <module>
client.run(TOKEN)
File "C:\Users\Adam\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\Adam\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\Adam\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 665, in start
await self.login(*args, bot=bot)
File "C:\Users\Adam\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip'
在我将变量移动到 .env
文件之前它工作正常。
#.py
import os
from dotenv import load_dotenv
import discord
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
GUILD = os.getenv("GUILD_NAME")
client = discord.Client()
@client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f"{client.user} is connected to the following guild:\n"
f"{guild.name}(id: {guild.id}"
)
client.run(TOKEN)
#.env
DISCORD_TOKEN=my_discord_token
GUILD_NAME=Testing
我的 .env
和 .py
在同一个文件夹中。
python-dotenv
的 load_env()
在与执行它的目录相同的目录中搜索 .env
文件。
如果您将 .env
文件名更改为自定义文件名,例如 var.env
,您必须指定文件名:load_env("var.env")