How to Run a Batch File from Python

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

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

import subprocess

subprocess.run([r"path where the batch file is stored\file_name.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.

You may then open Notepad and paste the script 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 be saved 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.run([r"path where the batch file is stored\file_name.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.run([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: Sat 03/23/2024'

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

Leave a Comment