Problem Formulation and Solution Overview
During your career as a Pythonista, you will encounter situations where a Python script will need to be executed on a scheduled basis, such as daily, weekly, or monthly.
This article shows you how to accomplish this task using a .bat
(batch) file.
Create a Python Script
Let’s first start by creating a Python script that counts down from five (5) to one (1).
In the current working directory, create a Python file called counter.p
y. Copy and paste the code snippet below into this file and save it.
from time import sleep lift_off = 5 while lift_off > 0: print (f'Lift Off in {lift_off} seconds!') sleep(2) lift_off -= 1
The first line in the above code snippet imports the time
library. This allows access to the sleep()
function, which pauses the script between iterations.
Next, a while
loop is instantiated and executes the code inside this loop until the value of lift_off
is zero (0).
On each iteration, the following occurs:
- A line of text is output to the terminal indicating the value of
lift_off
. - The script pauses for two (2) seconds.
- The value of
lift_off
is decreased by one (1).
To confirm script runs successfully. Navigate to the command prompt and run the following:
python counter.py
The output from this script should be as follows:
Lift Off in 5 seconds!
Lift Off in 4 seconds!
Lift Off in 3 seconds!
Lift Off in 2 seconds!
Lift Off in 1 seconds!
Great! Now let’s create a
(Batch) file to run this script!.bat
Create a .bat File
This section creates a .bat
file that executes counter.py
by calling this file inside the .bat
file.
In the current working directory, create a Python file called counter.bat
. Copy and paste the code snippet below into this file and save it.
@echo off "C:\Python\python.exe" "C:\PYTHON_CODE\counter.py"
The first line of the code snippet turns off any output to the terminal (except the code inside counter.py
). For example, If the first line (@echo off
) was removed and counter.bat
was executed, the following would be output to the terminal.
C:\WORK> "C:\Python\python.exe" "C:\PYTHON_CODE\counter.py"
Lift Off in 5 seconds!
Lift Off in 4 seconds!
Lift Off in 3 seconds!
Lift Off in 2 seconds!
Lift Off in 1 seconds!
The following line of code specifies the following:
- The location of the
python.exe
file on your computer. - The location of the python script to execute.
Let’s see if this works!
π‘ Note: It is best practice to ensure that the full paths to the python.exe
and counter.py
files are added.
Execute a .bat File
This section executes the .bat
file created earlier. This code calls and executes the code inside the counter.py
file.
To run the
file, navigate to the IDE, and click to select and highlight the .bat
counter.bat
file. Then, press the F5
key on the keyboard to execute.
If successful, the output should be the same as running the counter.py
file directly.
Lift Off in 5 seconds!
Lift Off in 4 seconds!
Lift Off in 3 seconds!
Lift Off in 2 seconds!
Lift Off in 1 seconds!
Perfect! Let’s schedule this to run Daily at a specified time.
Schedule a .bat File Using Windows Task Scheduler
This example uses Windows Task Scheduler to schedule a
file to run at a specified date/time..bat
To set up a Task Scheduler on Windows, navigate to the command prompt from Windows and run the following code:
taskschd.msc
Alternatively, click the Windows start button, search for, and select Task Scheduler.
Either of the above actions will display the Task Scheduler pop-up.
From the Actions area, click Create Basic Task. This action displays the Create a Basic Task Wizard pop-up.
From the Create a Basic Task pop-up, enter a Name and Description into the appropriate text boxes. Click the Next button to continue.
This action displays the Task Trigger pop-up. Select when to run the .bat
file. For this example, Daily was chosen. Click the Next button to continue.
Since Daily was selected earlier, the Daily pop-up displays. Modify the fields to meet the desired date and time requirements. Click the Next button to continue.
This action displays the Action pop-up. Select Start a program. Click the Next button to continue.
This action displays the Start a Program pop-up. Browse to select the counter.bat
file created earlier. Click the Next
button to continue.
This action displays the Summary pop-up. If satisfied with the selections made earlier, click the Finish button to complete the setup.
Great! The task is now scheduled to run at the date/time specified.
View, Edit, or Delete a Scheduled Task
To view a list of Scheduled Tasks, navigate to the Task Scheduler pop-up and select Task Scheduler Library.
To delete a task, click to select the appropriate task from the list of scheduled events. Then click the Delete link on the right-hand side.
To edit a task, click to select the appropriate task from the list of scheduled events. Then click the Properties link on the right-hand side to display the Properties pop-up. From this pop-up, all of the above selections can be modified.
Click the OK button to confirm any changes and close the pop-up.
π‘ Note: We recommend you review the fields on each tab to learn more about scheduling tasks.
Bonus: Schedule a Monthly .bat File
This section reads in a CSV containing sales data. This data is then sorted and filtered based on the current month. This is scheduled to run on the first day of each month. To follow along, download the CSV file.
In the current working directory, create a Python file called sales.py
. Copy and paste the code snippet below into this file and save it.
import pandas as pd from datetime import datetime import openpyxl today = datetime.now() cols = ['OrderDate', 'Region', 'Item', 'Units'] df = pd.read_csv('sales.csv', usecols=cols) df["OrderDate"] = pd.to_datetime(df["OrderDate"]) df = df.sort_values(by=['OrderDate']) df_monthly = df[df['OrderDate'].dt.month == today.month] df_monthly.to_excel('monthly_rpt.xlsx', columns=cols, index=False, header=True)
In the current working directory, create a Python file called sales.bat
Copy and paste the code snippet below into this file and save it. Modify to meet your locations.
@echo off "C:\Python\python.exe" "C:\PYTHON_CODE\sales.py"
Let’s set up a Monthly schedule to run on the first day of each month by performing the following steps:
- Start the Windows Task Scheduler.
- From the Task Scheduler pop-up, select Create Basic Task from the Actions area.
- From the Create a Basic Task pop-up, enter a Name and Description in the appropriate text boxes. Click the Next button to continue.
- From the Task Trigger pop-up, select Monthly. Click the Next button to continue.
- From the Monthly pop-up, complete the fields as outlined below:
- A Start Date and Start Time.
- From the Months dropdown, select each month that the report will run. For this example, all months were selected.
- From the Days dropdown, select the day(s) of the month to run this report. For this example, 1 was selected.
- Click the Next button to continue.
- From the Action pop-up, select Start a Program. Click the Next button to continue.
- From the Start a Program pop-up, click the Browse button to locate and select the
sales.bat
file. - From the Summary window click the Finish button.
This completes the configuration and activates the Scheduler to run on the specified day/time.
Summary
This article has shown you have to create and run a
file that executes a Python script on a scheduled basis..bat
Good Luck & Happy Coding!