How to Run a Batch File from Python – Data to Fish

In this short guide, you’ll see the steps to run any batch file from Python.

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

import subprocess
subprocess.call([r'path where the batch file is stored\name of the batch file.bat'])

Steps to Run a Batch File from Python

Step 1: Create a batch file

To start, create your batch file.

For demonstration purposes, let’s create a simple batch file that displays the date in green (note that the method described here would work for any batch file that you’d like to run from Python).

You may open Notepad and then copy the code below:

@echo off
color a & date
pause

To create the batch file, save the Notepad with a .bat extension. For example, let’s save the batch file as current_date.bat

A new batch file, called current_date.bat, would then get created at your specified location.

Step 2: Write the Python code

Here is a template that you can use to run a batch file from Python:

import subprocess
subprocess.call([r'path where the batch file is stored\name of the batch file.bat'])

For our example, let’s suppose that the batch file is stored in: C:\Users\Ron\Desktop\Test\current_date.bat

  • Where the name of the batch file is “current_date” and the file extension is “.bat”

Here is the complete code to run the batch file from Python for our example:

import subprocess
subprocess.call([r'C:\Users\Ron\Desktop\Test\current_date.bat'])

Note that you’ll need to modify the Python code to reflect the location where the batch file is stored on your computer.

Step 3: Run the Python code

Finally, run the Python code, and you’ll get the current date in green:

The current date is: Fri 06/25/2021

Alternatively, you may check the following guide that explains how to create a batch file to run a Python script.