分享:python+Windows自带任务计划程序,实现定时自动删微信的video文件夹

0. 背景

pc微信实在太占用磁盘空间了,特别是其中的视频文件夹。所以有了这些实现,每个月的最后一天的晚上的11点,自动删了微信的视频文件夹,从此不再面对红色磁盘的焦虑!
PS:本文章里的代码,98%是chatGPT生成的,我的作用是提问,总结和debug。。。。

1. 使用python实现删微信的video文件夹

1.1 代码

新建个python文件,命名为:delWechatFolder.py

import os
import shutil
import winreg

import click

CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])


@click.group(context_settings=CONTEXT_SETTINGS)
@click.version_option(version='1.0.0')
def myClick():
    """
        这是一个用于删除指定微信id的video文件夹的小工具。
    """
    pass


def getCurrentUserDocumentPath():
    '''通过注册表获取当前用户的document路径'''
    retPath = ""
    try:
        hKey = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                              "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders")
        retPath = winreg.QueryValueEx(hKey, "Personal")[0]
        winreg.CloseKey(hKey)
        print(retPath)
    except WindowsError as e:
        print("Error:", e)
    return retPath


def getWeChatFileSavePath():
    '''通过注册表获取微信文件保存路径'''
    retPath = None
    try:
        hKey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Tencent\\WeChat")
        retPath = winreg.QueryValueEx(hKey, "FileSavePath")[0]
        winreg.CloseKey(hKey)
    except WindowsError as e:
        print("Error:", e)
    if not retPath:
        retPath = getCurrentUserDocumentPath() + "\\WeChat Files"
    return retPath


@myClick.command()
@click.option('--wxid', default='scoful', prompt='要操作的微信id', help='要操作的微信id')
def delFolder(wxid):
    """删除指定wxid的video文件夹"""
    wechatFileSavePath = getWeChatFileSavePath()
    print(wechatFileSavePath)
    # 定义要删除的文件夹路径
    folder_path = wechatFileSavePath + "\\" + wxid + "\\FileStorage\\Video"
    # 判断文件夹是否存在
    if os.path.exists(folder_path):
        # 如果文件夹存在,就进入下一级目录
        os.chdir(folder_path)
        # 获取当前目录下的所有文件夹和文件
        file_list = os.listdir()
        # 遍历所有文件夹和文件
        for file_name in file_list:
            print(file_name)
            # 判断是否是文件夹
            if os.path.isdir(file_name):
                # 如果是文件夹,就使用 shutil.rmtree 函数删除该文件夹及其所有内容
                shutil.rmtree(file_name)
                print(f"文件夹 {file_name} 已删除")
    else:
        print("文件夹不存在")


if __name__ == '__main__':
    myClick()

1.2 打包

  • 为了方便使用和可以分享给他人使用,建议打包成可执行文件
  • 参考《科普:python怎么使用Pyinstaller模块打包成可执行文件》
  • 可选项,找个favicon.ico,可以通过这个网站自定义生成
  • 打包命令:Pyinstaller -F -c -i favicon.ico delWechatFolder.py
  • 切记在conda的虚拟环境里打包哦
  • 在代码目录下,会生成一个dist文件夹,里面就有生成的可执行文件,并且使用了提供的favicon.ico文件,delWechatFolder.exe

2. 使用python实现自动添加任务计划程序

任务计划程序的官方接口文档

2.1 代码

新建个python文件,命名为:registerMonthlyTask.py

import datetime
import os

import click
import win32com.client

CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])


@click.group(context_settings=CONTEXT_SETTINGS)
@click.version_option(version='1.0.0')
def myClick():
    """
        这是一个新建定时任务的小工具。
        每个月的最后一天删除指定微信id的video文件夹
    """
    pass


@myClick.command()
@click.option('--wxid', default='scoful', prompt='要操作的微信id', help='要操作的微信id')
def handleScheduler(wxid):
    # 创建任务计划程序对象
    scheduler = win32com.client.Dispatch("Schedule.Service")
    scheduler.Connect()

    # 获取任务计划程序的根文件夹
    root_folder = scheduler.GetFolder("\\")
    # 创建一个新任务
    task = scheduler.NewTask(0)

    # 设置任务的基本属性
    task.RegistrationInfo.Description = "每个月的最后一天删除指定微信id的video文件夹"
    task.Settings.Enabled = True
    task.Settings.Hidden = False

    # 创建每月最后一天晚上11点触发器
    trigger = task.Triggers.Create(4)  # 4 表示 MonthlyTrigger
    trigger.MonthsOfYear = 4095  # 4095 表示所有月份
    trigger.RunOnLastDayOfMonth = True  # True 表示每月最后一天
    trigger.StartBoundary = datetime.datetime.now().strftime('%Y-%m-%dT23:00:00')  # 每月最后一天晚上11点
    trigger.Id = 'delWechatFolder trigger'

    # 添加操作,用于调用.exe文件并传递额外参数
    action = task.Actions.Create(0)  # 0 表示 ExecAction
    current_directory = os.getcwd()
    print(current_directory)
    action.Path = current_directory + "\\delWechatFolder.exe"
    action.Arguments = "delfolder --wxid=" + wxid

    # 将任务添加到任务计划程序的根文件夹中
    root_folder.RegisterTaskDefinition(
        "delWechatFolder Task",
        task,
        6,  # 6 表示创建或更新任务
        "", "",  # 用户名和密码为空字符串,表示当前用户
        0)  # 0 表示不需要SDDL格式的安全描述符

    print("Task created successfully.")


if __name__ == '__main__':
    myClick()

2.2 打包

  • 为了方便使用和可以分享给他人使用,建议打包成可执行文件
  • 参考《科普:python怎么使用Pyinstaller模块打包成可执行文件》
  • 可选项,找个favicon2.ico,可以通过这个网站自定义生成
  • 打包命令:Pyinstaller -F -c -i favicon2.ico registerMonthlyTask.py
  • 切记在conda的虚拟环境里打包哦
  • 在代码目录下,会生成一个dist文件夹,里面就有生成的可执行文件,并且使用了提供的favicon.ico文件,registerMonthlyTask.exe

3. 使用bat脚本方便操作

3.1 手动删.bat

这个脚本是用来手动触发,并验证代码是否正确

@echo off
cd /d %cd%
start delWechatFolder.exe delfolder --wxid=你的微信id

3.2 加入定时任务.bat

这个脚本是用来加入任务计划程序

@echo off
cd /d %cd%
start registerMonthlyTask.exe handlescheduler --wxid=你的微信id

  • 双击运行后,可以去任务计划程序里查看是否加入,右键我的电脑-管理-任务计划程序库-任务计划程序库
    在这里插入图片描述
  • 可以看到已经新增成功
  • 右键该计划-运行,可以测试是否可以生效

enjoy!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值