繁体   English   中英

使用 Colab notebook 获取我们 google drive 中文件的可共享链接

[英]Get a shareable link of a file in our google drive using Colab notebook

谁能告诉我如何使用 Colab notebook 自动获取我们 google drive 中文件的可共享链接?

谢谢你。

您可以使用xattr获取 file_id

from subprocess import getoutput
from IPython.display import HTML
from google.colab import drive
drive.mount('/content/drive')  # access drive
# need to install xattr
!apt-get install xattr > /dev/null
# get the id
fid = getoutput("xattr -p 'user.drive.id' '/content/drive/My Drive/Colab Notebooks/R.ipynb' ")
# make a link and display it
HTML(f"<a href=https://colab.research.google.com/drive/{fid} target=_blank>notebook</a>")

在这里,我在/Colab Notebooks/R.ipynb访问我的笔记本文件,并创建一个链接以在 Colab 中打开它。

如果您查看文档,您会看到解释如何列出云端硬盘中的文件的部分。

使用它并阅读所用库的文档,我创建了这个脚本:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials

auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)

files = drive.ListFile().GetList()
for file in files:
  keys = file.keys()
  if 'webContentLink' in keys:
    link = file['webContentLink']
  elif 'webViewLink' in keys:
    link = file['webViewLink']
  else:
    link = 'No Link Available. Check your sharing settings.'

  if 'name' in keys:
    name = file['name']
  else:
    name = file['id']

  print('name: {}  link: {}'.format(name, link))

这当前列出了所有文件并提供了指向它的链接。

然后,您可以编辑 function 以查找特定文件。

希望这可以帮助!

就我而言,建议的解决方案不起作用。 所以我用“https://drive.google.com//file/d/”替换了colab URL

在我使用的下面:

def get_shareable_link(file_path):
  fid = getoutput("xattr -p 'user.drive.id' " + "'" + file_path + "'")
  print(fid)
  # make a link and display it
  return HTML(f"<a href=https://drive.google.com/file/d/{fid} target=_blank>file URL</a>")

get_shareable_link("/content/drive/MyDrive/../img_01.jpg")

get_output 没有在其他答案中为我定义,但是在执行 drive.mount 命令后,它起作用了:(test.zip 需要指向您的驱动器中的正确文件夹和文件:):

!apt-get install -qq xattr
filename = "/content/drive/My\ Drive/test.zip"
# Retrieving the file ID for a file in `"/content/drive/My Drive/"`:
id = !xattr -p 'user.drive.id' {filename}
print(id)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM