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

Windows任务计划运行Python shutil脚本仅复制首个文件求助

问题描述

编写了一个使用shutil.copy2的Python脚本,用于将指定文件夹内的文件复制到脚本自动创建的新文件夹中。手动运行脚本时可正常创建目录并完成所有文件复制;但通过Windows任务计划程序运行时,仅能创建目录并复制第一个文件,后续文件无法继续复制。已确认无需移除源文件(手动运行时源文件完整且脚本执行正常),且无法以「最高权限」运行该任务。

提供的三个脚本版本:

  • While循环版(任务计划下异常)
  • For循环版(任务计划下异常)
  • 指定文件名列表的简易版(任务计划下正常运行)
问题排查与修复方案

1. 路径拼接不规范引发的潜在问题

原脚本使用字符串拼接+ "/" +组合路径,在Windows环境下可能出现路径解析异常,建议统一使用os.path.join()处理路径,避免跨场景的格式错误。

2. 工作目录差异导致的日志写入异常

任务计划程序的默认工作目录并非脚本所在目录,原脚本中transfer_log.txt采用相对路径写入,可能会尝试写入系统目录(如C:\Windows\System32),触发权限不足导致脚本终止。需将日志文件改为绝对路径,确保写入权限。

3. 目录遍历逻辑的不确定性

While循环中反复调用os.listdir(src_path),虽手动运行正常,但任务计划下可能因环境差异导致遍历异常;For循环直接遍历os.listdir()结果,若遍历过程中源目录文件有变化也会引发问题。建议一次性获取符合条件的文件列表,避免反复遍历的不确定性。

修复后的脚本示例

import shutil
import os
import time
from datetime import datetime

# 配置核心路径
src_path = r"\\xxxx\xxx_Share\SAPextracts"
base_dst_path = r"\\xxxx\xxx_Share\gis\~ SAP IMPORTS"
today = datetime.today().strftime('%Y%m%d')
dst_path = os.path.join(base_dst_path, today)

# 创建目标目录(增加存在判断,避免重复创建报错)
if not os.path.exists(dst_path):
    os.mkdir(dst_path)

# 获取脚本所在目录,生成日志文件绝对路径
script_dir = os.path.dirname(os.path.abspath(__file__))
log_path = os.path.join(script_dir, 'transfer_log.txt')

# 一次性筛选出需要复制的文件(排除以arch开头的文件和目录)
src_files = [
    f for f in os.listdir(src_path) 
    if not f.startswith('arch') and os.path.isfile(os.path.join(src_path, f))
]

for file in src_files:
    src_file = os.path.join(src_path, file)
    dst_file = os.path.join(dst_path, file)
    
    try:
        start = time.time()
        shutil.copy2(src_file, dst_file)
        end = time.time()
        time_taken = round(end - start, 2)
        
        log_message = f"{datetime.now().replace(microsecond=0).isoformat()} - {src_file} 复制到 {dst_file},耗时 {time_taken} 秒"
        print(log_message)
        with open(log_path, 'a', encoding='utf-8') as f:
            f.write(log_message + '\n')
    except Exception as e:
        error_msg = f"{datetime.now().isoformat()} - 复制 {src_file} 失败: {str(e)}"
        print(error_msg)
        with open(log_path, 'a', encoding='utf-8') as f:
            f.write(error_msg + '\n')

额外注意事项

  • 确保任务计划的执行用户对源目录、目标目录及脚本所在目录拥有读取、写入、修改权限
  • 在任务计划的「操作」设置中,将「起始于」指定为脚本所在目录,避免工作目录异常
  • 异常捕获代码可帮助定位具体报错,方便进一步排查问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 07:25:17