如何修改现有代码获取Google Colab笔记本的完整路径?
获取Google Colab笔记本的完整Drive路径
问题原因
你调用的/api/sessions接口返回的path字段是Colab容器内部的临时文件路径,并非Google Drive中的实际存储路径,因此无法直接使用。
方案1:通过笔记本ID查询完整Drive路径
Colab笔记本的URL包含唯一文件ID,可借助这个ID调用Drive API获取真实存储路径。
代码示例:
from google.colab import auth from googleapiclient.discovery import build import requests from socket import gethostname, gethostbyname # 获取当前笔记本的文件ID ip = gethostbyname(gethostname()) session_data = requests.get(f"http://{ip}:9000/api/sessions").json()[0] notebook_id = session_data["id"] # 授权访问Drive API auth.authenticate_user() drive_service = build('drive', 'v3') # 递归拼接完整路径 def get_full_file_path(file_id, drive_service): path_segments = [] current_id = file_id while current_id: file_info = drive_service.files().get(fileId=current_id, fields='name,parents').execute() path_segments.append(file_info['name']) current_id = file_info.get('parents', [None])[0] return '/'.join(reversed(path_segments)) # 输出结果 full_path = get_full_file_path(notebook_id, drive_service) print("完整路径:", full_path) print("路径前缀:", '/'.join(full_path.split('/')[:-1]))
方案2:简化版(基于常见存储路径推断)
如果仅需路径前缀(如My Drive/Colab Notebooks),可结合Drive挂载和文件存在性检查快速获取:
from google.colab import drive from requests import get from socket import gethostname, gethostbyname import os # 挂载Drive drive.mount('/content/drive') # 获取当前笔记本文件名 ip = gethostbyname(gethostname()) filename = get(f"http://{ip}:9000/api/sessions").json()[0]["name"] # 常见Colab存储路径,可根据自身情况调整 common_storage_paths = [ "/content/drive/My Drive/Colab Notebooks", "/content/drive/My Drive" ] # 检查并输出匹配的路径 for path in common_storage_paths: if os.path.exists(f"{path}/{filename}"): print("路径前缀:", path.replace("/content/drive/", "")) break
注意事项
- 方案1需要完成Drive API授权,首次运行会弹出授权窗口,按提示操作即可。
- 方案2依赖常见存储路径,若笔记本存放在自定义文件夹,需手动添加路径到
common_storage_paths列表。
内容的提问来源于stack exchange,提问作者Rapsta
相关产品推荐
相关产品推荐

