![]() |
|
[Tut] How to Schedule a Batch Python Script - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Schedule a Batch Python Script (/thread-100219.html) |
[Tut] How to Schedule a Batch Python Script - xSicKxBot - 11-12-2022 How to Schedule a Batch Python Script 5/5 – (1 vote) 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 Code: .bat Question: How would we write code to run a Code: .batWe can accomplish this task by completing the following steps:
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 Code: counter.pCode: from time import sleep lift_off = 5 while lift_off > 0: print (f'Lift Off in {lift_off} seconds!') sleep(2) lift_off -= 1The first line in the above code snippet imports the Code: timeCode: sleep()Next, a Code: whileCode: lift_offOn each iteration, the following occurs:
To confirm script runs successfully. Navigate to the command prompt and run the following: Code: python counter.pyThe output from this script should be as follows: Code: 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 Code: .batCreate a .bat File This section creates a Code: .batCode: counter.pyCode: .batIn the current working directory, create a Python file called Code: counter.batCode: @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 Code: counter.pyCode: @echo offCode: counter.batCode: 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:
Let’s see if this works! Note: It is best practice to ensure that the full paths to the Code: python.exeCode: counter.pyExecute a .bat File This section executes the Code: .batCode: counter.pyTo run the Code: .batCode: counter.batCode: F5If successful, the output should be the same as running the Code: counter.pyCode: 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 Code: .batTo set up a Task Scheduler on Windows, navigate to the command prompt from Windows and run the following code: Code: taskschd.mscAlternatively, 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 Code: .bat![]() 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 Code: counter.batCode: Next![]() 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. [b][b]View, Edit, or Delete a Scheduled Task[/b][/b] 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 Code: sales.pyCode: 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 Code: sales.batCode: @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:
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 Code: .batGood Luck & Happy Coding! Programming Humor – Python [i]“I wrote 20 short programs in Python yesterday. It was wonderful. Perl, I’m leaving you.” — xkcd[/i]
|