Thonny插件调用_load_file加载远程文件报错求助
问题重现
尝试在Thonny插件中加载远程.py文件时,出现如下报错:
File "/Applications/Thonny.app/Contents/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/thonny/editors.py", line 193, in _load_local_file
with open(filename, "rb") as fp:
FileNotFoundError: [Errno 2] No such file or directory: 'https://raw.githubusercontent.com/thonny/thonny/3eaa0319a9722bcdac12b4401b0a69b47d2e9f00/thonny/first_run.py'
测试所用的远程文件为GitHub仓库中的first_run.py,插件代码中尝试通过self.editor._load_file()方法加载该远程URL,触发上述错误。
原因分析
Thonny编辑器的_load_file是仅用于加载本地文件的内部方法,它会调用_load_local_file,最终通过Python内置的open()函数读取路径。但open()只能处理本地文件系统路径,无法识别HTTP/HTTPS协议的远程URL,因此会把传入的URL当作本地文件路径去查找,自然找不到对应文件,抛出FileNotFoundError。
解决方法
不能直接用_load_file加载远程文件,需要先自行通过网络请求获取文件内容,再将内容写入编辑器。可以使用Python标准库urllib.request完成网络请求(无需额外安装依赖),再调用编辑器公开的set_text方法设置内容,可选标记文件名方便后续保存。
修改后的load_exercise方法代码如下:
def load_exercise(self) -> None: """Handle the plugin execution.""" self.editor = self.workbench.get_editor_notebook().get_current_editor() self.filename = self.editor.get_filename() if self.filename is not None and self.filename[-3:] == ".py": self.editor.save_file() # 远程文件URL remote_url = "https://raw.githubusercontent.com/thonny/thonny/3eaa0319a9722bcdac12b4401b0a69b47d2e9f00/thonny/first_run.py" try: # 用标准库获取远程文件内容 from urllib.request import urlopen with urlopen(remote_url) as response: content = response.read().decode("utf-8") # 设置编辑器内容 self.editor.set_text(content) # 可选:标记编辑器的文件名,方便后续保存时识别 self.editor.set_filename(remote_url) except Exception as e: from tkinter.messagebox import showerror showerror(title="Exercise Loader", message=f"加载失败:{str(e)}") return showinfo(title="Exercise Loader", message="OK")
补充说明
urllib.request.urlopen负责从远程获取文件内容,解码为UTF-8文本适配Python文件的常见编码。set_text是Thonny编辑器公开的API,适合直接向编辑器写入内容,比内部方法_load_file更符合这种场景的需求。set_filename为可选操作,设置后编辑器会将该URL作为当前文件标识,后续保存时会提示用户选择本地路径,避免误操作远程文件。
内容的提问来源于stack exchange,提问作者limitcracker

