Python - 从 Google 驱动器下载文件作为计划任务

Python - Download files from Google Drive as a scheduled task

是的,我知道类似的问题已经得到回答,但它必须作为一个周期性工作(来自 Windows 任务调度程序,每天晚上 21:00)这一事实才是重点问题。

我有一个 python 脚本,可以将单个 google 电子表格下载为 .xlsx 并将其保存在网络文件夹中。该脚本在从命令行启动时有效,在从 .bat(在计划任务中调用的那个)执行时也有效。

除了网络文件夹中没有文件外,该任务似乎工作正常。 我想这是许可和身份验证的问题,尽管如果手动 运行,在第一次保留身份验证详细信息后它会在没有任何弹出窗口的情况下工作,所以我不明白为什么,通过调度程序,它应该有权限问题。

我试过运行它也用网络管理员的帐户,但没有用。

我再说一遍,脚本本身工作正常,当 运行 通过调度程序时它什么都不做(并且 return 没有任何错误)。这不是我安排的第一个 python 脚本,但我仍然可能遗漏了一些东西。

谢谢


我正在添加脚本,我从中删除了文件 ID 和网络路径。

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import io

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']


def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)

    # Call the Drive v3 API
    file_id = 'ID_OF_THE_SPREADSHEET'
    request = service.files().export_media(fileId=file_id,
                                           mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    fh = io.BytesIO()
    downloader = MediaIoBaseDownload(fh, request)
    done = False
    while done is False:
        status, done = downloader.next_chunk()
        print("Download %d%%." % int(status.progress() * 100))
    with open("FILEPATH_OF_THE_NET_FOLDER", "wb") as f:  # Excel File
        f.write(fh.getbuffer())


if __name__ == '__main__':
    main()

我自己回答,问题不在于凭据,而在于文件路径。 今天我了解到:使用相对路径和计划任务不是一个好主意。