How to Create a Batch File to Run Python Script

In this tutorial, I’ll show you the steps to create a batch file to run a Python script using a simple example.

But before we dive into the example, here is the batch file template that you can use to run the Python script:

"Path where your Python exe is stored\python.exe" "Path where your Python script is stored\script name.py"
pause

In the next section, I’ll review an example to create a batch file that will launch the Python GUI below. The same concepts would apply for any Python script that you’d like to run using a batch file.

Batch File to Run Python Script

Steps to Create a Batch File to Run Python Script

Step 1: Create the Python Script

To start, create your Python Script.

For example, I used the below code to create a simple GUI with a single button to exit the application.

Alternatively, you may use any Python code that you’d like.

import tkinter as tk 

root= tk.Tk() 
   
canvas1 = tk.Canvas(root, width = 300, height = 300) 
canvas1.pack()
      
button1 = tk.Button (root, text='Exit Application', command=root.destroy) 
canvas1.create_window(150, 150, window=button1) 
    
root.mainloop()

Step 2: Save your Script

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

In my case, I saved the Python script as simple_gui

py file

Step 3: Create the Batch File

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

"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 code in two places:

  • “Path where your Python exe is stored\python.exe”
    In my case, the Python exe is located at: “C:\Users\Ron\AppData\Local\Programs\Python\Python37-32\python.exe”
  • “Path where your Python script is stored\script name.py”
    And in my case, the Python script that I wish to run is located at:
    “C:\Users\Ron\Desktop\MyPython\simple_gui.py”

This is how my batch script would look like in Notepad:

 

How to Create a Batch File to Run Python Script

 

Now save the Notepad with a ‘bat’ extension. Here, I named the batch file as Run_Script.bat:

Notepad bat

Step 4: Run the Batch File

Your batch file is now ready to go. Double-click on that batch file:

Your Python script will run now…

For our example, the Python GUI will be displayed as follows:

Batch File to Run Python Script

That’s it, mission accomplished!

Conclusion

You just saw how to create a batch file to run a Python script. There might be opposite cases, where you may need to run a batch file from Python itself.

You may also want to check the following tutorials on batch scripts: