python之小脚本大威力(一)--文件备份

国庆在家没事的时候,拿起一本python语法,花了几个小时简单学习了下语法知识。就想着用python写点使用的东西。正好最近写了几篇文章,用到了很多素材什么的,这些文件十分的重要,所以需要备份。想到了用C++来写,又费劲不讨好。正好python用上了,github上走一走。

废话不说上代码:

# -*- coding: utf-8 -*-import hashlib
import os
import shutil
​
​
success_copy = []
failed_copy = []
​
​
def md5check(filename):
    m = hashlib.md5()
    # 以二进制的方式打开文件
    with open(filename, 'rb') as f:
        while True:
            # 只读取前面4字节
            data = f.read(4096)
            if not data:
                break
            m.update(data)
    return m.hexdigest()
​
​
def copy(path):
    new_path = path
    new_path = new_path.replace(old_source, new_source)
    # print(new_path)
    # 如果是个文件类型,则需要比较md5值
    if os.path.isfile(new_path):
        old_md5 = md5check(path)
        new_md5 = md5check(new_path)
        # md5一致则说明文件没有变化,不需要copy
        if old_md5 != new_md5:
            try:
                shutil.copy(path, new_path)
                success_copy.append(path)
            except:
                failed_copy.append(path)
    # 如果是文件夹,则需要创建文件夹
    else:
        dirname = os.path.dirname(new_path)
        if os.path.exists(dirname):
            shutil.copy(path, new_path)
            success_copy.append(path)
        else:  # 目录不存在,则直接创建目录并复制文件
            try:
                os.makedirs(dirname)
                shutil.copy(path, new_path)
            except WindowsError:
                failed_copy.append("create dir failed:" + path)
​
​
# 查找所有目录文件的递归函数
def lsdir(folders):
    path = os.listdir(folders)
    for line in path:
        line = folders + '/' + line
        if os.path.isdir(line):
            lsdir(line)
        else:
            copy(line)
​
​
if __name__ == '__main__':
    print("start back up file...")
    global old_source
    global new_source
    # 需要备份的目录,备份到新目录
old_source = "G:/code/code_git/xd"
# 备份到新目录
    new_source = "F:/13_bak"
    lsdir(old_source)
​
    count = 1
    if len(success_copy) != 0:
        for item in success_copy:
            # print(count + ":" + item)
            print("{0} {1}".format(count, item))
            count += 1
    else:
        print("back file empty.")print("---------------------------------------------")
​
    count = 1
    if len(failed_copy) != 0:
        for item in failed_copy:
            print("{0} {1}".format(count, item))
            count += 1
    else:
        print("back file error empty.")
    print("---------------------------------------------")print("back up file finished...")

写着写着,新需求又来了。不能让我每次手动去执行这个脚本吧,但是要是写个死循环一直跑着,那多浪费资源,最好是能够定时那种的。这种事情在linux使用crontab那就是分分钟搞定,但是在windows还真有点麻烦。在windows上其实也有这种功能就是计划任务,需要用户手动的设置比较繁琐还不容易搞定,有一些参数需要设定。转念一想,咱是程序员,不能这么low,能代码搞定的事绝对不动手click,更重要的是写完了下次说不定哪里又能复用上了。

因为创建计划任务的代码比较多,这里我就贴出主要的代码

/****************************************************************************
**
** Copyright (C) 2019 635672377@qq.com
** All rights reserved.
**
****************************************************************************/#ifndef win7taskscheduler_h
#define win7taskscheduler_h#include <vector>
#include <utility>
#include <string>#include <assert.h>#include <comdef.h>
#include <taskschd.h>#pragma comment(lib, "taskschd.lib")using std::pair;
using std::vector;
using std::wstring;
using std::to_wstring;namespace XIBAO {class Win7TaskScheduler{
public:
    Win7TaskScheduler() {}
    ~Win7TaskScheduler() {}private:
class ITaskServiceHelper
{
public:
    ITaskServiceHelper()        {   p = NULL;   }
    ~ITaskServiceHelper()       {   if ( p ) p->Release();  }
​
    ITaskService * p;
};class ITaskFolderHelper
{
public:
    ITaskFolderHelper()         {   p = NULL;   }
    ~ITaskFolderHelper()        {   if ( p ) p->Release();  }
​
    ITaskFolder * p;
};class ITaskDefinitionHelper
{
public:
    ITaskDefinitionHelper()     {   p = NULL;   }
    ~ITaskDefinitionHelper()    {   if ( p ) p->Release();  }
​
    ITaskDefinition * p;
};class IRegistrationInfoHelper
{
public:
    IRegistrationInfoHelper()   {   p = NULL;   }
    ~IRegistrationInfoHelper()  {   if ( p ) p->Release();  }
​
    IRegistrationInfo * p;
};class IPrincipalHelper
{
public:
    IPrincipalHelper()          {   p = NULL;   }
    ~IPrincipalHelper()         {   if ( p ) p->Release();  }
​
    IPrincipal * p;
};class ITaskSettingsHelper
{
public:
    ITaskSettingsHelper()       {   p = NULL;   }
    ~ITaskSettingsHelper()      {   if ( p ) p->Release();  }
​
    ITaskSettings * p;
};class ITriggerCollectionHelper
{
public:
    ITriggerCollectionHelper()  {   p = NULL;   }
    ~ITriggerCollectionHelper() {   if ( p ) p->Release();  }
​
    ITriggerCollection * p;
};class ITriggerHelper
{
public:
    ITriggerHelper()            {   p = NULL;   }
    ~ITriggerHelper()           {   if ( p ) p->Release();  }
​
    ITrigger * p;
};class IDailyTriggerHelper
{
public:
    IDailyTriggerHelper()           {   p = NULL;   }
    ~IDailyTriggerHelper()          {   if ( p ) p->Release();  }
​
    IDailyTrigger * p;
};class IRegistrationTriggerHelper
{
public:
    IRegistrationTriggerHelper(){   p = NULL;   }
    ~IRegistrationTriggerHelper(){  if ( p ) p->Release();  }
​
    IRegistrationTrigger * p;
};class IActionCollectionHelper
{
public:
    IActionCollectionHelper()   {   p = NULL;   }
    ~IActionCollectionHelper()  {   if ( p ) p->Release();  }
​
    IActionCollection * p;
};class IActionHelper
{
public:
    IActionHelper()             {   p = NULL;   }
    ~IActionHelper()            {   if ( p ) p->Release();  }
​
    IAction * p;
};class IExecActionHelper
{
public:
    IExecActionHelper()         {   p = NULL;   }
    ~IExecActionHelper()        {   if ( p ) p->Release();  }
​
    IExecAction * p;
};class IRegisteredTaskHelper
{
public:
    IRegisteredTaskHelper()     {   p = NULL;   }
    ~IRegisteredTaskHelper()    {   if ( p ) p->Release();  }
​
    IRegisteredTask * p;
};#define DO( action )        \
    if( FAILED( action ) )  \
{                       \
    assert( FALSE );    \
    return FALSE;       \
}public:
static bool Create2MoreWin7(const wstring &appPath,
                            const wstring &taskName,
                            const wstring &taskDescription,
                            const wstring &appWorkDir,
                            const wstring &parameter,
                            const vector<pair<int, int>> &vecTime)
{
    CoInitialize(NULL);
​
    HRESULT hr = 0;
    ITaskServiceHelper iService;
​
    hr = CoCreateInstance( CLSID_TaskScheduler,
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           IID_ITaskService,
                           (void**)&iService.p);
    
    //  Connect to the task service.
    DO( iService.p->Connect( _variant_t(), _variant_t(), _variant_t(), _variant_t()) )//  Get the pointer to the root task folder.  This folder will hold the
    //  new task that is registered.
    ITaskFolderHelper iRootFolder;
    DO( iService.p->GetFolder( _bstr_t( L"\\") , &iRootFolder.p ) )
    
    ITaskFolderHelper iNewFolder;
    IRegisteredTaskHelper iRegisteredTask;
    ITaskDefinitionHelper iTask;
    BOOL bTmp = FALSE;
    /*
    if(! appWorkDir.empty()){
        hr = iRootFolder.p->GetFolder(_bstr_t(appWorkDir.c_str()),&iNewFolder.p);
        if(hr  != S_OK){
            hr = iRootFolder.p->CreateFolder(_bstr_t(appWorkDir.c_str()),
                _variant_t(), &iNewFolder.p); //使用默认的安全描述符
            if(FAILED(hr))
            {
                return FALSE;
            }
        }
        hr = iNewFolder.p->GetTask(_bstr_t(taskName.c_str()),&iRegisteredTask.p);
        if(hr != S_OK) {
            return FALSE;
        }
    }
    else{
        hr = iRootFolder.p->GetTask(_bstr_t(taskName.c_str()),&iRegisteredTask.p);
    }
    */DO( iService.p->NewTask( 0, &iTask.p ) )
    // DO( iService->NewTask( 0, &iTask.p ) )
​
    IRegistrationInfoHelper info;
    DO(iTask.p->get_RegistrationInfo(&(info.p)))
    if (nullptr != info.p) { 
        (info.p)->put_Description(_bstr_t(taskDescription.c_str())); 
    }
​
    IActionCollectionHelper iActionCollection;
    DO( iTask.p->get_Actions( &iActionCollection.p ) )
​
    IActionHelper iAction;
    DO( iActionCollection.p->Create( TASK_ACTION_EXEC, &iAction.p ) )
​
    IExecActionHelper iExecAction;
    //  QI for the executable task pointer.
    DO( iAction.p->QueryInterface( 
        IID_IExecAction, (void**) &iExecAction.p ) )//  Set the path of the executable to notepad.exe.
    DO( iExecAction.p->put_Path( _bstr_t( appPath.c_str() ) ) )if(! parameter.empty())
    {
        DO( iExecAction.p->put_Arguments(_bstr_t(parameter.c_str())))
    }if(! appWorkDir.empty())
    {
        DO( iExecAction.p->put_WorkingDirectory(_bstr_t(appWorkDir.c_str())))
    }
​
    ITriggerCollectionHelper iTriggerCollection;
    DO( iTask.p->get_Triggers( &iTriggerCollection.p ) )
​
    ITaskSettingsHelper iTaskSettings; 
    DO( iTask.p->get_Settings(&iTaskSettings.p) )
​
    iTaskSettings.p->put_DisallowStartIfOnBatteries(VARIANT_BOOL(FALSE));
    iTaskSettings.p->put_StopIfGoingOnBatteries(VARIANT_BOOL(FALSE));{
        for (int i = 0; i < vecTime.size(); ++i) {
            ITriggerHelper iTrigger;
            DO( iTriggerCollection.p->Create( TASK_TRIGGER_DAILY,
                                                &iTrigger.p ) )
​
            IDailyTrigger *dailyTriger = nullptr;
            iTrigger.p->QueryInterface(IID_IDailyTrigger, 
                                        (void **)&dailyTriger); 
            if (nullptr != dailyTriger) {
                wstring triggerid = taskName + L"_" + to_wstring(i);
                dailyTriger->put_Id(_bstr_t(triggerid.c_str()));
                dailyTriger->put_DaysInterval(1);
                wstring strstarttime = L"2019-01-01T" + to_wstring(vecTime[i].first) + L":" + to_wstring(vecTime[i].second) + L":00";
                dailyTriger->put_StartBoundary(_bstr_t(strstarttime.c_str()));
                dailyTriger->put_EndBoundary(_bstr_t(L"2099-12-31T00:00:00"));
                dailyTriger->put_Enabled(true);
            }
        }
    }
​
    IPrincipalHelper iPrincipal;
    DO( iTask.p->get_Principal( &iPrincipal.p ) )
    DO(iPrincipal.p->put_RunLevel(TASK_RUNLEVEL_LUA))
    hr = iRootFolder.p->RegisterTaskDefinition(
                                                _bstr_t(taskName.c_str()),
                                                iTask.p,
                                                TASK_CREATE_OR_UPDATE, 
                                                _variant_t(), 
                                                _variant_t(), 
                                                TASK_LOGON_INTERACTIVE_TOKEN,
                                                _variant_t(L""),
                                                &iRegisteredTask.p);return true;
}static bool Delete2MoreWin7(const wstring &taskName)
{
    ITaskServiceHelper iService;
    HRESULT hr = CoCreateInstance( CLSID_TaskScheduler,
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           IID_ITaskService,
                           (void**)&iService.p );
        
    DO( iService.p->Connect(_variant_t(), 
                            _variant_t(), 
                            _variant_t(), 
                            _variant_t()))
​
    ITaskFolderHelper iRootFolder;
    DO( iService.p->GetFolder( _bstr_t( L"\\") , &iRootFolder.p ) )
    
    IRegisteredTaskHelper iRegisteredTask;
    ITaskDefinitionHelper iTask;
​
    hr = iRootFolder.p->GetTask(_bstr_t(taskName.c_str()),&iRegisteredTask.p);
    hr = iRootFolder.p->DeleteTask(_bstr_t(taskName.c_str()),0);return true;
}};};
#endif // win7taskscheduler_h

最后看计划任务有没有创建成功,win+R打开运行框,输入taskschd.msc,在弹出的面板,可以看到你说创建的计划任务名称。

计划任务如果创建,尝试着以管理员身份运行并暂时关闭杀软。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值