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

Python脚本在IDE正常运行,Windows任务计划程序无法执行的原因

脚本无输出且不执行删除操作的问题排查与修复

我用高权限运行任务,权限应该没问题。这个脚本的作用是自动删除早于指定日期且超过设定大小的文件,但不管是通过任务计划程序执行,还是手动用管理员权限打开,它都是打开后直接关闭,既没有输出也不删除该处理的文件。我已经把所需库装到系统路径里了,问题还是没解决。

原代码

import datetime
from dateutil.relativedelta import relativedelta


def Setup():
    Directories = open("Directories.txt", "r")
    dir = Directories.readline().rstrip()
    Directories.close()

    FSFile = open("FileSizeMax.txt", "r")
    FileSizeMax = FSFile.readline().rstrip()
    FSFile.close()

    Exclusions = open("Exclusions.txt", "r")
    ExclusionList = [line.rstrip() for line in Exclusions]
    Exclusions.close()

    lastDate = datetime.datetime.now() - relativedelta(weeks=1)
    formattedDate = lastDate.strftime("%m/%d/%Y")
    return dir, FileSizeMax, ExclusionList, formattedDate


# Get clips in directory
def getFiles(dirs):
    list = []
    list = os.listdir(dirs)
    return list


# Delete any clips older than the last date and larger than the MB set in the FileSizeMax.txt. Exclude any thing set in exclusions file.
def delFiles(files, FileSizeMax, ExclusionList, dirs, lastdate):
    print(files)
    lDate = datetime.datetime.strptime(lastdate, "%m/%d/%Y")
    for file in files:
        print(file)
        path = os.path.join(dirs, file)
        print(path)
        timecreated = os.path.getctime(path)
        size = os.path.getsize(path) >> 20
        date = datetime.datetime.fromtimestamp(timecreated).strftime("%m/%d/%Y")
        parseddate = datetime.datetime.strptime(date, "%m/%d/%Y")
        print(f'{file} created on {date} and is {size} MB\n')
        if date not in ExclusionList and size > FileSizeMax and parseddate <= lDate:
            print(f"Delete {file} {date} {size} MB")
            os.remove(path)


dirList, FileSizeMax, ExclusionList, lastmonth = Setup()
print(dir)
print(FileSizeMax)
print(ExclusionList)
maxFile = int(FileSizeMax)
files = getFiles(dirList)
delFiles(files, maxFile, ExclusionList, dirList, lastmonth)

核心问题点

  • 缺少os模块导入:代码大量使用os模块函数(如os.listdir、os.path.join),但未导入import os,运行时直接触发NameError导致脚本崩溃退出,无任何输出。
  • 变量名错误:主程序中print(dir)打印的是Python内置函数dir(),而非Setup函数返回的目标目录,正确应为print(dirList)。
  • 排除逻辑错误:代码判断date not in ExclusionList,但Exclusions.txt的作用是排除特定文件名,而非日期,正确逻辑应为file not in ExclusionList。
  • 日期处理冗余:将文件创建时间戳转成字符串再解析为datetime对象,完全可以直接用datetime.datetime.fromtimestamp(timecreated)与目标日期比较,减少转换步骤避免错误。
  • 无异常处理:未处理文件缺失、目录无权限等异常,一旦出现问题脚本直接崩溃。
  • 手动运行无暂停:手动执行时脚本完毕立即关闭窗口,即使有输出也无法查看。

修正后的代码

import os
import datetime
from dateutil.relativedelta import relativedelta


def Setup():
    try:
        with open("Directories.txt", "r") as dir_file:
            target_dir = dir_file.readline().rstrip()
        
        with open("FileSizeMax.txt", "r") as fs_file:
            max_size_str = fs_file.readline().rstrip()
            max_size = int(max_size_str)
        
        with open("Exclusions.txt", "r") as excl_file:
            exclusion_list = [line.rstrip() for line in excl_file]
        
        last_date = datetime.datetime.now() - relativedelta(weeks=1)
        return target_dir, max_size, exclusion_list, last_date
    except FileNotFoundError as e:
        print(f"错误:找不到文件 - {e.filename}")
        input("按回车键退出...")
        exit(1)
    except ValueError:
        print("错误:FileSizeMax.txt中不是有效的数字")
        input("按回车键退出...")
        exit(1)


def get_files(target_dir):
    try:
        return os.listdir(target_dir)
    except PermissionError:
        print(f"错误:无权限访问目录 {target_dir}")
        input("按回车键退出...")
        exit(1)
    except FileNotFoundError:
        print(f"错误:目录 {target_dir} 不存在")
        input("按回车键退出...")
        exit(1)


def delete_files(files, max_size, exclusion_list, target_dir, cutoff_date):
    print(f"待处理文件列表:{files}\n")
    for file in files:
        if file in exclusion_list:
            print(f"跳过排除文件:{file}")
            continue
        
        file_path = os.path.join(target_dir, file)
        # 跳过子目录,只处理文件
        if not os.path.isfile(file_path):
            print(f"跳过非文件:{file_path}")
            continue
        
        try:
            # 获取文件创建时间(Windows下是创建时间,Linux下是元数据修改时间)
            create_time = os.path.getctime(file_path)
            create_datetime = datetime.datetime.fromtimestamp(create_time)
            # 转换文件大小为MB
            file_size = os.path.getsize(file_path) >> 20
            
            print(f"文件:{file} | 创建时间:{create_datetime.strftime('%m/%d/%Y')} | 大小:{file_size} MB")
            
            if create_datetime <= cutoff_date and file_size > max_size:
                print(f"删除文件:{file}")
                os.remove(file_path)
            else:
                print(f"不满足删除条件,跳过:{file}")
        except PermissionError:
            print(f"错误:无权限操作文件 {file_path}")
        except Exception as e:
            print(f"处理文件 {file} 时出错:{str(e)}")
        print("---")


if __name__ == "__main__":
    target_dir, max_size, exclusion_list, cutoff_date = Setup()
    print(f"目标目录:{target_dir}")
    print(f"最大文件大小(MB):{max_size}")
    print(f"排除文件列表:{exclusion_list}")
    print(f"截止日期:{cutoff_date.strftime('%m/%d/%Y')}\n")
    
    files = get_files(target_dir)
    delete_files(files, max_size, exclusion_list, target_dir, cutoff_date)
    
    input("按回车键退出...")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 00:55:11