Colab、kaggle亲测可行,思路是使用onedrive的sdk进行验证,并使用相关函数进行上传和下载。
有时Colab/Kaggle在运行过程中途突然断连,又是临时虚拟机就会丢失运行文件,这时候就可以运行文件保存到Onedrive网盘上。
脚本代码存放在github库
欢迎访问个人博客。
验证
首先安装库:
!pip install onedrivesdk
!pip3 install git+https://github.com/OneDrive/onedrive-sdk-python.git
!pip3 install --upgrade git+https://github.com/OneDrive/onedrive-sdk-python.git
获取验证的代码如下,需要填入的是client_secret,client_id:
import onedrivesdk
redirect_uri = 'https://od.cnbeining.com'
client_secret = 'your_client_secret'
client_id = 'your_client_id'
api_base_url = 'https://api.onedrive.com/v1.0/'
scopes=['wl.signin', 'wl.offline_access', 'onedrive.readwrite']
http_provider = onedrivesdk.HttpProvider()
auth_provider = onedrivesdk.AuthProvider(
http_provider=http_provider,
client_id=client_id,
scopes=scopes)
client = onedrivesdk.OneDriveClient(api_base_url, auth_provider, http_provider)
auth_url = client.auth_provider.get_auth_url(redirect_uri)
# Ask for the code
print('Paste this URL into your browser, approve the app\'s access.')
print('Copy everything in the address bar after "code=", and paste it below.')
print(auth_url)
code = input('Paste code here: ')
client.auth_provider.authenticate(code, redirect_uri, client_secret)
-
首先在Azure 应用程序管理器注册一个应用。
-
获取client_id,为框中所示:

- 获取client_secert,为步骤3所示:
- 身份验证设置重定向
- 运行
获取验证
的代码,输入浏览器中出现的code复制到框内即可。
相关操作
最常用的是上传和下载,其他详见https://github.com/OneDrive/onedrive-sdk-python。
上传文件
假如我要将colab
的README.md上传到onedrive
的new_dir/文件夹下:
upload_file="/content/sample_data/README.md"
onedrive_savefile="new_dir/README.md"
client.item(drive='me', path=onedrive_savefile).upload(upload_file)
onedrive的保存路径不用新建。
下载文件
假如我要将onedrive
的new_dir/README.md文件下载到colab
的/content/temp/目录下:
onedrive_download_file="new_dir/README.md"
save_file="/content/temp/README.md"
client.item(drive='me',path=onedrive_download_file).download(save_file)
colab的保存路径需要存在。
BUG
验证部分的代码我已经改好了,直接拿来就可以用,以下是使用官方代码出现的BUG。
-
code = raw_input('Paste code here: ')
的raw_input改为input。 -
redirect_uri = 'http://localhost:8080/'
的重定向uri改为https://od.cnbeining.com。 -
唯一不好的地方是必须知道Onedrive的确切文件地址才可以实现上述操作…不能真正像挂载硬盘那种查找啥的。
脚本文件
-
安装环境
sh onedrive.sh
-
参考验证步骤,将client_secret和client_id填入验证函数中。
每次验证需要填写code,验证成功后接着进行上传和下载。 -
上传
- 单个文件:
python onedrive.py upload file -i local_file/to/upload -o onedrive_path/to/save
- 多个文件:
python onedrive.py upload file -i local_file1/to/upload local_file/to/upload ... -o onedrive_path/to/save
- 文件夹:
python onedrive.py upload folder -i local_path/to/upload -o onedrive_path/to/save
- 单个文件:
-
下载
- 单个文件:
python onedrive.py download file -i onedrive_file/to/download -o local_path/to/save
- 多个文件:
python onedrive.py download file -i onedrive_file1/to/download onedrive_file2/to/download... -o local_path/to/save
- 单个文件: