【发布时间】:2022-01-14 15:33:48
【问题描述】:
我正在用 python 做一个简单的不和谐机器人,我正在使用 heroku 来托管它。我有一些返回大文本的命令,所以我将这些文本放在单独的 .txt 文件中,并将所有这些文件组织在一个名为“文件”的文件夹中。然后我使用代码访问和读取这些文件。当我托管机器人时一切正常,但 heroku 在托管时总是返回“FileNotFoundError”。
完整的错误信息:
Ignoring exception in command helpie:
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.10/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/app/main.py", line 27, in helpie
helpmessage = open(".\files\helpMessage.txt", "r", encoding = "utf-8")
FileNotFoundError: [Errno 2] No such file or directory: '.\x0ciles\\helpMessage.txt'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/app/.heroku/python/lib/python3.10/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/app/.heroku/python/lib/python3.10/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: FileNotFoundError: [Errno 2] No such file or directory: '.\x0ciles\\helpMessage.txt'
这是使用 .txt 文件的命令之一。此代码位于 heroku 正在读取的 main.py 文件中。
@bot.command()
async def helpie(ctx):
helpmessage = open(".\files\helpMessage.txt", "r", encoding = "utf-8")
await ctx.send(helpmessage.read())
helpmessage.close()
这是程序根文件夹及其所有文件的树:
C:.
│ .gitignore
│ main.py
│ Procfile
│ README.md
│ requirements.txt
│ runtime.txt
│
├───.vscode
└───files
bot icon.png
geraldoMessage.txt
helpMessage.txt
不知道有没有必要,不过我也会把“requirements.txt”和“Procfile”的内容包括进去。
过程文件:
worker: python main.py
requirements.txt
discord.py
asyncio
感谢您的帮助。
【问题讨论】:
-
您是否尝试过使用 heroku 中文件的绝对路径来提供给
open()语句?此外,如果 heroku 使用/作为路径分隔符,您尝试访问的文件可能具有不同的路径。 -
我不会使用绝对路径,因为这几乎肯定会在环境之间有所不同(特别是在 Heroku 和似乎是本地 Windows 机器之间)。但我会建议使路径相对于已知位置。现在它与工作目录相关。
-
完整的错误信息是什么?我怀疑你得到了类似
No such file or directory: '.\x0ciles\\helpMessage.txt'的东西?
标签: python file heroku discord discord.py