How to Create a Batch File to Run a Python Script

In this guide, you’ll see the steps to create a batch file to run a Python script.

To start, here is a batch file template that you can use to run your Python script:

@echo off
"Path where your Python exe is stored\python.exe" "Path where your Python script is stored\script_name.py"
pause

Steps to Create a Batch File to Run a Python Script

Step 1: Create the Python Script

To begin, create your Python Script.

For example, let’s create a simple Python script that contains a countdown (alternatively, you may use any Python script):

import time

countdown = 5

while countdown > 0:
    print('Countdown = ', countdown)
    countdown = countdown - 1
    time.sleep(1)

Step 2: Save your Script

Save your Python script (your Python script should have the extension of ‘.py‘).

For our example, let’s save the Python script as: final_countdown.py

  • Where the file extension is .py

Step 3: Create the Batch File to Run the Python Script

To create the batch file, open Notepad and then use the following template:

@echo off
"Path where your Python exe is stored\python.exe" "Path where your Python script is stored\script_name.py"
pause

You’ll need to adjust the syntax in two places:

(1) “Path where your Python exe is stored\python.exe”
You can locate the path where your Python exe is stored by following these steps:

  • Type “Python” in the Windows Search Bar
  • Right-click on the Python App, and then select “Open file location
  • Right-click again on the Python shortcut, and then select “Open file location

Here is an example of a path where the Python exe is located (don’t forget to add “\python.exe” at the end of the path):

"C:\Users\Ron\AppData\Local\Programs\Python\Python311\python.exe"

(2) “Path where your Python script is stored\script_name.py”
Here is an example of a path where the Python script is located (don’t forget to add “.py” at the end of the path):

"C:\Users\Ron\Desktop\Test\final_countdown.py"

Note that you’ll need to change the paths based on where the files are stored on your computer.

This is how the batch script would look like in Notepad for our example:

@echo off
"C:\Users\Ron\AppData\Local\Programs\Python\Python311\python.exe" "C:\Users\Ron\Desktop\Test\final_countdown.py"
pause

Save the Notepad with a ‘.bat‘ extension. For example, let’s save the Notepad as run_countdown.bat

A new batch file, called “run_countdown.bat,” will be created at your specified location.

Step 4: Run the Batch File

Finally, double-click on the batch file in order to run the Python script.

You’ll then get the countdown as follows:

Countdown =  5
Countdown =  4
Countdown =  3
Countdown =  2
Countdown =  1

You may also want to check the following source that contains additional guides about batch scripts.