【问题标题】:Will not load json file with json.load [closed]不会使用 json.load 加载 json 文件 [关闭]
【发布时间】:2022-01-23 22:15:31
【问题描述】:

使用我的不和谐机器人,我正在尝试将一堆不同命令的响应存储在一个 json 文件中。该命令只是一组胆量,键为“胆量”,值是一个包含不同字符串的列表。当我使用with open() 函数时,它会将其注册为一个目录,您可以打印原始文件,但是当您尝试使用var = json.load 时,它什么也做不了。该行之后的任何代码都不会运行。

我使用 shell 命令直接进入该文件并打开它。这完全没问题。文件打印正常。

    @commands.command()
    async def dare(self, ctx):
        """Gives the user a dare to do"""
    
        with open("cogs/docs/json/responses.json") as f:
            print(-1)
            print(f)
            data = json.load(f)
            print(0)
            dares = data["dare"]
            print(1)
            selectedDare = random.choice(dares)

        await ctx.reply(selectedDare)

上面的代码只打印到-1f。没有什么过不去的。 f 只是打印对象。我也试过json.loads 等,没有任何效果。 JSON 正确安装。我完全迷路了。

所有的响应都存储在一个列表中,这是仅用于此命令的响应。

// this is all the responses for the dares
    {
        "dare":[
            "Dare #1",
            "Dare #2",
            "Dare #3"
        ]
    }

我的机器人处理错误有一个 CommandError,但没有进一步的。


# if a command flags an error it handles it
@client.event
async def on_command_error(ctx, error):
    """Handles errors"""

    if isinstance(error, commands.CommandError):
        print("CommandError found")
        return

【问题讨论】:

  • 你有错字吗?您的代码有:dares = data["dares"],但您发布了一些 json 与:{ "dare":[ ... ] }
  • 啊,这是一个错字,谢谢,但正如帖子中所说,代码甚至没有出现在那里。我还将 json 文件编辑为 3 个字符串而不是原来的 40+,所以我可能忘记了最后的 s ..
  • 也许json.load() 会导致异常。它是否在其他地方被捕获并被忽略?
  • ...请求minimal reproducible example 的部分目的是为了让我们可以捕获上述异常处理之类的内容,而无需玩 20 个问题。
  • ...问题中包含的代码应该是最短的可能会导致在没有任何更改的情况下运行时询问确切错误的内容。这段代码在没有更改的情况下运行会导致不同的错误(没有imports,没有该方法所属的类,等等)。

标签: python json python-3.x discord.py pycord


【解决方案1】:

如 cmets 中所述,问题来自作者定义 on_command_erroron_error 函数(https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=on_command_error#discord.ext.commands.Bot.on_command_error

当它在 bot/cog 中的任何地方引发时,将被调用并带有异常/错误。

-> 定义的函数应该总是有一个默认情况,例如,如果你写了几个if isinstance(e, SomeException): ...,你将需要一个else: raise eelse: super().on_command_error(e) 来确保进一步处理默认情况,在您没有计划或您不需要在机器人/cog 中担心的异常情况

你可以把你的函数改成这个

# if a command flags an error it handles it
@client.event
async def on_command_error(ctx, error):
    """Handles errors"""

    if isinstance(error, commands.CommandError):
        print("CommandError found")
        return
    super().on_command_error(ctx, error)

或者这个

# if a command flags an error it handles it
@client.event
async def on_command_error(ctx, error):
    """Handles errors"""

    if isinstance(error, commands.CommandError):
        print("CommandError found")
        return
    raise error

但我认为最好的方法是

# if a command flags an error it handles it
@client.event
async def on_command_error(ctx, error):
    """Handles errors"""

    if isinstance(error, commands.CommandError):
        print("CommandError found")
    else:
        super().on_command_error(ctx, error)

当添加其他条件时,例如其他错误,您将不得不使用elif

【讨论】:

  • 您将如何添加super().on_command_error(e)
  • 紧跟在您的print("CommandError found") return 之后,以便在条件为假的情况下执行,我将编辑我的答案
  • 出现此错误Ignoring exception in on_command_error Traceback (most recent call last): File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "main.py", line 210, in on_command_error super().on_command_error(ctx, error) RuntimeError: super(): __class__ cell not found
  • 那我认为你不能 super() 那里,但重新提出错误总是有效的,所以尝试raise error的解决方案,你的回溯会更长但它会准确跨度>
  • 如果您想要类似 JSON 但带有 cmets 的东西,请考虑 YAML。 (是的,有些 YAML 看起来根本不像 JSON,但所有 JSON 都是有效的 YAML,所以你只需将 json 模块换成 YAML 解析器就可以了)
猜你喜欢
  • 2020-09-29
  • 2016-11-03
  • 2022-01-02
  • 2021-01-17
  • 2020-05-18
  • 2022-12-12
  • 2018-05-17
  • 2019-03-26
  • 1970-01-01
相关资源
最近更新 更多