如何用Python从GitHub下载Git LFS托管的exe文件
问题解决:下载GitHub上Git LFS托管的EXE文件
关于GitHub是否允许EXE文件
GitHub完全允许上传和下载EXE格式文件。仅对非Git LFS托管的单个文件有100MB大小限制,超过该限制的文件必须通过Git LFS上传,这也是你当前使用LFS的原因。
为什么你的代码无法下载目标文件
当文件通过Git LFS上传后,GitHub仓库中实际存储的是一个LFS指针文件(而非原始EXE文件)。你原本调用的contents接口返回的是这个指针文件的base64编码内容,解码后并不是有效的EXE数据,因此无法正常保存为可执行文件。
修正后的下载代码
需要先通过contents接口获取LFS文件的实际下载链接,再直接请求该链接获取原始文件内容:
import requests import base64 import shutil def download_file_from_github(repo_owner, repo_name, file_path, access_token): api_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/contents/{file_path}" headers = { "Accept": "application/vnd.github+json", "Authorization": f"Bearer {access_token}" } response = requests.get(api_url, headers=headers) if response.status_code == 200: data = response.json() # 处理Git LFS托管的文件 if data.get("type") == "file" and "lfs" in data: lfs_download_url = data["lfs"]["download_url"] lfs_response = requests.get(lfs_download_url, stream=True, headers=headers) if lfs_response.status_code == 200: return lfs_response.raw else: print(f"下载LFS文件失败,状态码: {lfs_response.status_code}") return None # 处理普通非LFS文件 else: content = data.get("content", "") decoded_content = base64.b64decode(content) return decoded_content else: print(f"获取文件信息失败,状态码: {response.status_code}") return None if __name__ == "__main__": repo_owner = "NguyenDucQuan12" repo_name = "Update_app" file_path = "QSV-VN/app/QSV-VN.exe" access_token = "xxxxxxxxxxx" file_content = download_file_from_github(repo_owner, repo_name, file_path, access_token) if file_content: with open("QSV-VN.exe", "wb") as f: if isinstance(file_content, bytes): f.write(file_content) else: shutil.copyfileobj(file_content, f) print("文件下载成功。")
代码说明
- 新增LFS文件判断逻辑:检查返回的JSON数据中是否包含
lfs字段,以此识别LFS托管文件 - 获取LFS实际下载链接:从
data["lfs"]["download_url"]拿到原始文件的下载地址 - 流式下载LFS文件:使用
stream=True流式获取大文件,避免内存占用过高 - 兼容普通文件:保留原有的非LFS文件处理逻辑,确保代码能同时处理两种类型的文件
内容的提问来源于stack exchange,提问作者Nguyễn Đức Quân
相关产品推荐
相关产品推荐

