下面的代碼在 Amazon Linux 2 上運行時會產生此錯誤。目的是讓 python 程式回應來自 discord 服務器的用戶輸入。我知道的足以讓我了解 Python。任何幫助表示贊賞。他們的服務器正在運行 Amazon Linux 2 的更新版本。
File "./bot.py", line 65, in <module>
client.run(os.environ[config.discord_key])
File "/usr/lib64/python3.7/os.py", line 681, in __getitem__
raise KeyError(key) from None
KeyError: 'SuperSecretSquirrelStuff-key'
import discord, asyncio, os, boto3, config
client = discord.Client()
ec2 = boto3.resource('ec2')
instance_id = config.instance_id
#Temp
instance = ec2.Instance(instance_id)
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------------')
@client.event
async def on_message(message):
memberIDs = (member.id for member in message.mentions)
if client.user.id in memberIDs:
if 'stop' in message.content:
if turnOffInstance():
await client.send_message(message.channel, 'AWS Instance stopping')
else:
await client.send_message(message.channel, 'Error stopping AWS Instance')
elif 'start' in message.content:
if turnOnInstance():
await client.send_message(message.channel, 'AWS Instance starting')
else:
await client.send_message(message.channel, 'Error starting AWS Instance')
elif 'state' in message.content:
await client.send_message(message.channel, 'AWS Instance state is: ' getInstanceState())
elif 'reboot' in message.content:
if rebootInstance():
await client.send_message(message.channel, 'AWS Instance rebooting')
else:
await client.send_message(message.channel, 'Error rebooting AWS Instance')
def turnOffInstance():
try:
instance.stop(False, False)
return True
except:
return False
def turnOnInstance():
try:
instance.start()
return True
except:
return False
def getInstanceState():
return instance.state['Name']
def rebootInstance():
try:
instance.reboot()
return True
except:
return False
client.run(os.environ[config.discord_key])```
uj5u.com熱心網友回復:
根據您的錯誤資訊,您的系統中沒有環境變數“SuperSecretSquirrelStuff-key”。
這是可以重現您的問題的代碼:
import os
print(os.environ["ANY_KEY_NOT_EXIST"])
要解決此問題,您應該將環境變數“SuperSecretSquirrelStuff-key”添加到您的系統中。
例如,在終端 shell 中執行此代碼行:
export SuperSecretSquirrelStuff-key=xxx
順便說一下,環境密鑰“SuperSecretSquirrelStuff-key”可能無效。
uj5u.com熱心網友回復:
您正在嘗試從系統環境變數中讀取,該變數顯然尚未設定,因此KeyError(因為SuperSecretSquirrelStuff-key不作為 中的鍵存在os.environ)。
我可以看到您之前使用過該config物件來讀取,例如,instance_id.
在這種情況下,直接從您的配置中讀取,而不是os.environ如果您想要的值discord_key:
client.run(config.discord_key)
或者(不知道為什么要這樣做)在閱讀之前設定環境變數:
os.environ[config.discord_key] = "VALUE";
client.run(os.environ[config.discord_key])
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/341854.html
上一篇:將C專案轉換為庫以在QT中使用
下一篇:查找在特定檔案中找到文本的目錄
