11-09-2022, 09:53 PM
How to Create and Run a Batch File That Runs a Python Script?
5/5 – (1 vote)
Problem Formulation and Solution Overview
This article will show you how to create and execute a batch file in Python.
Info: A batch or file is a file that contains commands to be executed in the order specified. This file type can organize and automate tasks that need to be run regularly without requiring user input. These files can be created using a text editor, such as Notepad.
To make it more interesting, we have the following running scenario:
The Sales Manager of Suppliworks has asked you to create and send him a Monthly Sales Report. This file will arrive as an unsorted, unfiltered CSV. You will need to filter this criterion based on the current month and save it as an Excel file to the current working directory.
Download the file to follow along with our article.
Question: How would we write code to create and execute a batch file in Python?
We can accomplish this task by completing the following steps:
Install Batch Runner Extension
To run/execute a file, an extension will need to be installed in the IDE.
To install this extension, navigate to the IDE, area. In the VSC IDE, this can be found on the far left panel bar shown below.
In the Search textbox, enter Batch Runner. While entering this text, the IDE automatically searches for extensions that match the criteria entered.
Once the desired extension is found, click the Install button to the left of the Batch Runner extension to start the installation process.
![[Image: bat_001aa-1024x380.png]](https://blog.finxter.com/wp-content/uploads/2022/11/bat_001aa-1024x380.png)
Once the installation has been completed, the Install button converts to a Settings icon. The extension is now ready to use!
![[Image: bat_002a-1024x253.png]](https://blog.finxter.com/wp-content/uploads/2022/11/bat_002a-1024x253.png)
Note: Feel free to install the Batch Extension of your choosing.
Create Python Script
This section creates a Python file that reads in a CSV, sorts, filters and saves the output to an Excel file.
You can replace this with any Python file you want to run. For this example, we’ll need two libraries:
To install those libraries, navigate to the IDE terminal command prompt. Enter and run the two commands to install both libraries:
In the current working directory, create a Python file called.
Copy and paste the code snippet below into this file and save it.
The first three (3) lines in the above code snippet import references to the libraries necessary to run this code error-free.
The following line retrieves the current date usingfrom the library. The results save to the variable . If the contents were output to the terminal, the following displays:
The next line declares a List containing the DataFrame Columns to retrieve from the CSV file and export to the Excel file. The results save to.
Then, the file is opened, and columns specified in are retrieved. The results save to the DataFrame . If was output to the terminal, the following snippet displays:
Top Five (5) Records of
|
OrderDate |
Region |
Item |
Units
0 |
11/6/2022 |
East |
Pencil |
95
1 |
11/23/2022 |
Central |
Binder |
50
2 |
11/9/2022 |
Central |
Pencil |
36
3 |
11/26/2022 |
Central |
Pen |
27
4 |
11/15/2022 |
West |
Pencil |
56
The next line converts the into a proper Date format.
|
OrderDate |
Region |
Item |
Units
0 |
2022-11-06 |
East |
Pencil |
95
1 |
2022-11-23 |
Central |
Binder |
50
2 |
2022-11-09 |
Central |
Pencil |
36
3 |
2022-11-26 |
Central |
Pen |
27
4 |
2022-11-15 |
West |
Pencil |
56
As you can see, the DataFrame,, is not in any kind of sort order. The next line takes care of this by sorting on the field in ascending order. The results save back to the DataFrame .
|
OrderDate |
Region |
Item |
Units
22 |
2022-01-15 |
Central |
Binder |
46
23 |
2022-02-01 |
Central |
Binder |
87
24 |
2022-02-18 |
East |
Binder |
4
25 |
2022-03-07 |
West |
Binder |
7
26 |
2022-03-24 |
Central |
Pen Set |
50
This script’s final two (2) lines filter the DataFrame,, based on the current month. The results save to . These results are then exported to Excel and placed into the current working directory.
If you run this code, you will see that the Excel file saved the appropriate filtered results into the file.
![[Image: bat_005.png]](https://blog.finxter.com/wp-content/uploads/2022/11/bat_005.png)
Great! Now let’s create a Batch file to run this script!
Create Batch File
In this section, a file is created to run the Python file .
In the current working directory, create a file called .
Copy and paste the code snippet below into this file and save it.
The first line of the code snippet turns off any output to the terminal.
The following line specifies the following:
Let’s see if this works!
Execute
This section executes the file, which calls and runs the code inside the file.
To run the file, navigate to the IDE, and click to select the file.
Press the key on the keyboard to execute.
If successful, the file will appear in the current working directory!
Summary
This article has shown you have to create and run a file that executes a Python script. This file can execute a simple Python script as well as an intricate one.
Good Luck & Happy Coding!
5/5 – (1 vote)
Problem Formulation and Solution Overview
This article will show you how to create and execute a batch file in Python.
Info: A batch or Code:
.batTo make it more interesting, we have the following running scenario:
The Sales Manager of Suppliworks has asked you to create and send him a Monthly Sales Report. This file will arrive as an unsorted, unfiltered CSV. You will need to filter this criterion based on the current month and save it as an Excel file to the current working directory.
Download the
Code:
sales.csv
Question: How would we write code to create and execute a batch file in Python?We can accomplish this task by completing the following steps:
- Install the Batch Runner Extension
- Create the Python Script
- Create the fileCode:
.bat
- Execute
Install Batch Runner Extension
To run/execute a
Code:
batTo install this extension, navigate to the IDE,
Code:
ExtensionsIn the Search textbox, enter Batch Runner. While entering this text, the IDE automatically searches for extensions that match the criteria entered.
Once the desired extension is found, click the Install button to the left of the Batch Runner extension to start the installation process.
![[Image: bat_001aa-1024x380.png]](https://blog.finxter.com/wp-content/uploads/2022/11/bat_001aa-1024x380.png)
Once the installation has been completed, the Install button converts to a Settings icon. The extension is now ready to use!
![[Image: bat_002a-1024x253.png]](https://blog.finxter.com/wp-content/uploads/2022/11/bat_002a-1024x253.png)
Note: Feel free to install the Batch Extension of your choosing.Create Python Script
This section creates a Python file that reads in a CSV, sorts, filters and saves the output to an Excel file.
You can replace this with any Python file you want to run. For this example, we’ll need two libraries:
- The library will need to be installed for this example, as the code reads in and filters a CSV file.Code:
pandas
- The library will need to be installed for this example, as the code exports the filtered DataFrame to an Excel file. To install this library, navigate to the IDE terminal command prompt. Enter and run the code snippet shown below.Code:
openpyxl
To install those libraries, navigate to the IDE terminal command prompt. Enter and run the two commands to install both libraries:
Code:
pip install pandas
pip install openpyxlIn the current working directory, create a Python file called
Code:
sales.pyCopy and paste the code snippet below into this file and save it.
Code:
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)The first three (3) lines in the above code snippet import references to the libraries necessary to run this code error-free.
The following line retrieves the current date using
Code:
datetime.now()Code:
datetimeCode:
todayCode:
2022-11-08 07:59:00.875656The next line declares a List containing the DataFrame Columns to retrieve from the CSV file and export to the Excel file. The results save to
Code:
colsThen, the
Code:
sales.csvCode:
colsCode:
dfCode:
dfTop Five (5) Records of
Code:
sales.csv|
OrderDate |
Region |
Item |
Units
0 |
11/6/2022 |
East |
Pencil |
95
1 |
11/23/2022 |
Central |
Binder |
50
2 |
11/9/2022 |
Central |
Pencil |
36
3 |
11/26/2022 |
Central |
Pen |
27
4 |
11/15/2022 |
West |
Pencil |
56
The next line converts the
Code:
OrderDate|
OrderDate |
Region |
Item |
Units
0 |
2022-11-06 |
East |
Pencil |
95
1 |
2022-11-23 |
Central |
Binder |
50
2 |
2022-11-09 |
Central |
Pencil |
36
3 |
2022-11-26 |
Central |
Pen |
27
4 |
2022-11-15 |
West |
Pencil |
56
As you can see, the DataFrame,
Code:
dfCode:
OrderDateCode:
df|
OrderDate |
Region |
Item |
Units
22 |
2022-01-15 |
Central |
Binder |
46
23 |
2022-02-01 |
Central |
Binder |
87
24 |
2022-02-18 |
East |
Binder |
4
25 |
2022-03-07 |
West |
Binder |
7
26 |
2022-03-24 |
Central |
Pen Set |
50
This script’s final two (2) lines filter the DataFrame,
Code:
dfCode:
df_monthlyIf you run this code, you will see that the Excel file saved the appropriate filtered results into the
Code:
monthly_rpt.xlsx![[Image: bat_005.png]](https://blog.finxter.com/wp-content/uploads/2022/11/bat_005.png)
Great! Now let’s create a Batch file to run this script!
Create Batch File
In this section, a
Code:
batCode:
sales.pyIn the current working directory, create a
Code:
batCode:
sales.batCopy and paste the code snippet below into this file and save it.
Code:
@echo off "C:\Python\python.exe" "sales.py"The first line of the code snippet turns off any output to the terminal.
The following line specifies the following:
- The location of the file on your computer.Code:
python.exe
- The Python script to execute.
Let’s see if this works!
Execute
This section executes the
Code:
batCode:
sales.pyTo run the
Code:
batCode:
sales.batPress the
Code:
F5If successful, the
Code:
monthly_rpt.xlsxSummary
This article has shown you have to create and run a
Code:
.batGood Luck & Happy Coding!

