我正在用 python 做一個簡單的不和諧機器人,我正在使用 heroku 來托管它。我有一些回傳大文本的命令,所以我將這些文本放在單獨的 .txt 檔案中,并將所有這些檔案組織在一個名為“files”的檔案夾中。然后我使用代碼訪問和讀取這些檔案。當我托管機器人時一切正常,但 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
要求.txt
discord.py
asyncio
感謝您的幫助。
uj5u.com熱心網友回復:
我懷疑一個更完整的錯誤是這樣的:
No such file or directory: '.\x0ciles\\helpMessage.txt'
直接的問題可能是您不小心使用了轉義序列,包括\f在您的字串中,這表示 ASCII 表單提要。
請注意,路徑已被破壞。您可以在這里使用原始字串:
open(r".\files\helpMessage.txt", "r", encoding = "utf-8")
# ^ raw string
或者您可以更改定義該路徑的方式。正斜杠比反斜杠更安全,并且使用pathlibor將各個路徑組件連接在一起os.path更安全。
我認為這不是您的直接問題,但您的路徑也與作業目錄有關。我建議將其設定為相對于已知位置,例如專案的根目錄。
把它們放在一起,嘗試這樣的事情(使用pathlib):
from pathlib import Path
# This will point to the right directory no matter what the working directory is
root_path = Path(__file__).resolve().parent
@bot.command()
async def helpie(ctx):
helpmessage = open(root_path / "files" / "helpMessage.txt", "r", encoding = "utf-8")
# ^ ^ safely joining components
# ^^^^^^^^^ known path
await ctx.send(helpmessage.read())
helpmessage.close()
或像這樣(使用os.path):
import os.path
root_path = os.path.dirname(os.path.abspath(__file__))
@bot.command()
async def helpie(ctx):
helpmessage = open(os.path.join(root_path, "files", "helpMessage.txt"), "r", encoding = "utf-8")
# ^^^^^^^^^ known path
# ^^^^^^^^^^^^ safely joining components
await ctx.send(helpmessage.read())
helpmessage.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/413533.html
標籤:
上一篇:在c 中包含兩個頭檔案
