You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本通过Windows任务计划程序上传Google Drive失败求助

Windows任务计划程序执行Google Drive上传脚本失败的问题排查与解决

问题描述

我需要通过Windows任务计划程序自动将照片上传到Google Drive。手动运行Python脚本时上传正常,但将脚本加入批处理文件后,通过任务计划程序执行却没有任何上传动作。

我的Python上传脚本

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive


gauth = GoogleAuth()           
drive = GoogleDrive(gauth)  



upload_file_list = ['ex_photo_name1.jpg', 'ex_photo_name2.jpg']
for upload_file in upload_file_list:

    gauth = GoogleAuth()
    # Try to load saved client credentials
    gauth.LoadCredentialsFile("mycreds.txt")
    if gauth.credentials is None:
        # Authenticate if they're not there
        gauth.LocalWebserverAuth()
    elif gauth.access_token_expired:
        # Refresh them if expired
        gauth.Refresh()
    else:
        # Initialize the saved creds
        gauth.Authorize()
    # Save the current credentials to a file
    gauth.SaveCredentialsFile("mycreds.txt")
    
    drive = GoogleDrive(gauth)
    
    textfile = drive.CreateFile()
    textfile.SetContentFile(upload_file)
    textfile.Upload()

    
    drive.CreateFile({'id':textfile['id']}).GetContentFile(upload_file)

批处理文件内容

@echo off
python "path\to\python\Setup.py" %*
python "path\to\python\script.py" %*
pause

排查与解决步骤

1. 修正文件路径问题

任务计划程序的默认工作目录和手动运行时不一致,相对路径会导致文件找不到:

  • 将脚本中所有相对路径改为绝对路径,比如:
    gauth.LoadCredentialsFile("C:\\full\\path\\to\\mycreds.txt")
    upload_file_list = ['C:\\full\\path\\to\\ex_photo_name1.jpg', 'C:\\full\\path\\to\\ex_photo_name2.jpg']
    
  • 批处理文件中的Python脚本路径也必须使用绝对路径。

2. 统一Python环境

手动运行用的是当前用户的Python环境,任务计划程序可能调用系统默认Python或未加载虚拟环境:

  • 批处理中使用Python的绝对路径,比如C:\\Users\\YourName\\AppData\\Local\\Programs\\Python\\Python311\\python.exe代替python;
  • 若使用虚拟环境,先激活环境再执行脚本:
    @echo off
    call "C:\\full\\path\\to\\venv\\Scripts\\activate.bat"
    python "C:\\full\\path\\to\\Setup.py" %*
    python "C:\\full\\path\\to\\script.py" %*
    pause
    

3. 优化认证逻辑

  • LocalWebserverAuth()需要弹出浏览器授权,任务计划后台执行时无法触发,需先手动运行脚本生成mycreds.txt并确保路径正确;
  • 将认证逻辑移到循环外,避免重复初始化:
    from pydrive.auth import GoogleAuth
    from pydrive.drive import GoogleDrive
    
    # 认证逻辑移到循环外
    gauth = GoogleAuth()
    gauth.LoadCredentialsFile("C:\\full\\path\\to\\mycreds.txt")
    if gauth.credentials is None:
        gauth.LocalWebserverAuth()
    elif gauth.access_token_expired:
        gauth.Refresh()
    else:
        gauth.Authorize()
    gauth.SaveCredentialsFile("C:\\full\\path\\to\\mycreds.txt")
    
    drive = GoogleDrive(gauth)
    
    upload_file_list = ['C:\\full\\path\\to\\ex_photo_name1.jpg', 'C:\\full\\path\\to\\ex_photo_name2.jpg']
    for upload_file in upload_file_list:
        textfile = drive.CreateFile()
        textfile.SetContentFile(upload_file)
        textfile.Upload()
        # 不需要下载回本地可删除此行
        # drive.CreateFile({'id':textfile['id']}).GetContentFile(upload_file)
    

4. 检查任务计划程序配置

  • 安全选项选择不管用户是否登录都要运行,按需勾选不存储密码;
  • 操作中的程序或脚本填写批处理文件绝对路径,起始于设置为批处理文件所在目录;
  • 暂时取消隐藏选项,显示窗口运行查看是否有报错。

5. 添加日志定位错误

  • 批处理中添加日志输出:
    @echo off
    call "C:\\full\\path\\to\\venv\\Scripts\\activate.bat"
    python "C:\\full\\path\\to\\Setup.py" >> "C:\\full\\path\\to\\task_log.txt" 2>&1
    python "C:\\full\\path\\to\\script.py" >> "C:\\full\\path\\to\\task_log.txt" 2>&1
    pause
    
  • Python脚本中添加日志:
    import logging
    logging.basicConfig(filename='C:\\full\\path\\to\\script_log.txt', level=logging.INFO)
    
    # 关键步骤加日志
    for upload_file in upload_file_list:
        logging.info(f"开始上传: {upload_file}")
        try:
            textfile = drive.CreateFile()
            textfile.SetContentFile(upload_file)
            textfile.Upload()
            logging.info(f"{upload_file} 上传成功")
        except Exception as e:
            logging.error(f"{upload_file} 上传失败: {str(e)}")
    

内容的提问来源于stack exchange,提问作者Mitchell Nelson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 06:25:34