Using Python to perform scheduled Windows tasks


Ever since Guido van Rossum introduced Python in 1991, it has  arguably become the favorite programming language for both programmers and non-professional programmers. While Python is used extensively in scientific and data computing, with it's easy extensibility and availability of several packages, it is also a handy tool for doing operating system scripting jobs which are usually done by sh/bash scripts in Unix flavor operating systems and by batch (*.bat) scripts in Windows.

In this article, we take a look a simple Python script which replaces a Window batch script and is scheduled to run weekly through the Windows tasks scheduler. The original batch script takes weekly backup of a folder into an external drive. Only one copy of the backup folder is required hence the existing backup folder is deleted before the copy (this to ensure there is space for copying the new folder). The backup folder should also be inside folder(s) that represent the date the copy was made.

This batch script is scheduled through a task scheduler to run once a week and its code is given below:


@echo off
K:
cd "K:\Dasmic\Backup\"
REM Remove existing folder
rmdir Company /s/q
for /f "tokens=1* delims=" %%a in ('date /T') do set datestr=%%a
mkdir %datestr%
REM Start copy of files
robocopy "C:\Dasmic\Company" "K:\Dasmic\Backup\Company\%datestr%" /MIR


As one can see, getting the current date is not straightforward. In this case, the script creates multiple folders each for month, data and year which is not exactly a clean approach.

The following code is for a Python script doing the same task. The packages shutil, datetime and os are used for this and using the datetime.date.today() function we get a formatted string for the folder name which is the passed to create the folder. The code is also much cleaner to read:

#Script to backup folder - Chaitanya Belwal, cbelwal@gmail.com
import shutil
import datetime
from os import makedirs

#set common variables
baseSourceFolder = "C:\Dasmic\Company"
baseTargetFolder = "K:\Dasmic\Backup\Company"

#Remove existing folder
print("Deleting existing folder ...\r\n")
shutil.rmtree(baseTargetFolder)
dateTime=datetime.date.today().strftime("%Y_%B_%d")
targetFolder= baseTargetFolder + "\\" + dateTime #'2018_May_10'
print("Creating new folder ...\r\n")

# Start copy of files
print("Starting copy ...\r\n")
shutil.copytree(baseSourceFolder,targetFolder)


This script is now set up to run automatically via the task scheduler using the following steps:

1. Start 'Task Scheduler' from Control Panel/Administrative Tools:


2. From 'Action' menu, selected 'Create New Task...'.The following window will come up:


3. Add a new 'Trigger' to set the date/time to run the Python Script:


4. Add a new action to run the Python interpreter with the path of the script passed as command line parameter.
  (Note that if you have installed Python independently without Anaconda, the path to Python.exe will be different:)


The Python script is now scheduled to run at the date and time specified by the trigger.


Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. have you compared the speed vs robocopy ? - i'd imagine python is slower - and will it work with destinations and / or sources on a LAN ?

    ReplyDelete

Post a Comment

Popular posts from this blog

Part III: Backpropagation mechanics for a Convolutional Neural Network

Introducing Convolution Neural Networks with a simple architecture

Deriving Pythagoras' theorem using Machine Learning