【问题标题】:Key error while running a Python program with getitem使用 getitem 运行 Python 程序时出现关键错误
【发布时间】:2021-12-14 10:24:19
【问题描述】:

以下代码在 Amazon Linux 2 上运行时会产生此错误。目的是让 python 程序响应来自不和谐服务器的用户输入。我知道的足以让我了解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])```

【问题讨论】:

  • 是否设置了环境变量SuperSecretSquirrelStuff-key
  • 我还有一个名为 config.py 的文件,其中包含一个设置为 instance_id 和 discord_key 的变量。这里的 SSSS-key 是我的实际令牌的占位符,它存储在 config.py 中并返回错误。

标签: python linux amazon-ec2 keyerror


【解决方案1】:

您正在尝试从系统环境变量中读取,该变量显然尚未设置,因此 KeyError(因为 SuperSecretSquirrelStuff-keyos.environ 中不作为键存在)。

我可以看到您之前使用过config 对象来读取,例如instance_id

在这种情况下,如果您想要 discord_key 的值,请直接从您的配置中读取,而不是执行 os.environ

client.run(config.discord_key)


或者(不知道为什么要这样做)在读取环境变量之前设置它:

os.environ[config.discord_key] = "VALUE";
client.run(os.environ[config.discord_key])

【讨论】:

  • 天啊!你是一个美丽的人类!谢谢你。我现在觉得很傻,但我花了太多时间盯着这个想法......它传递了变量但没有工作。这是有道理的,感谢您扩展您的流程。
  • 哈哈,谢谢 :) 周末愉快,在 AWS 上玩得开心!
【解决方案2】:

根据您的错误信息,您的系统中没有环境变量“SuperSecretSquirrelStuff-key”。

这里的代码可以重复你的问题:

import os
print(os.environ["ANY_KEY_NOT_EXIST"])

要解决此问题,您应该在系统中添加环境变量“SuperSecretSquirrelStuff-key”。

例如,在终端 shell 中执行以下代码行:

export SuperSecretSquirrelStuff-key=xxx

顺便说一句,环境密钥“SuperSecretSquirrelStuff-key”可能无效。

【讨论】:

  • 感谢您的回复!我在一个名为 config 的依赖项中声明了这个变量,该依赖项被导入。该变量名为 discord_key 并包含一个字符串,该字符串是我的 discord 机器人的令牌。当我返回此错误时,将我的令牌显示为字符串。
  • 我需要把这个导出放在哪里?
  • 这个解决方案也可以!我选择走一条不同的路线,以便让我的大脑更有条理,但是,感谢您的时间和投入!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 2019-03-27
  • 1970-01-01
  • 2022-09-22
  • 1970-01-01
  • 2021-07-18
  • 1970-01-01
相关资源
最近更新 更多