Python: Running executables using subprocess module

There are many ways to run a bat/exe file but the most widely used is the subprocess module.
And I would like to clearly show, how exactly to do that. When should you use what arguments.
I am going to specifically talk about the check_output module .

Note : This function is used when we want the output of the bat file collected inside a variable.

Condition 1: The exe file is in the same location as of the python script that wants to run it.

You are in a Folder > MyPrograms  . And the bat/exe file lies inside this folder. (Refer picture below)

Single folder with bat and python files

Content of the hello.bat file

@echo off
echo "This is a test bat"

My script contents:

import subprocess
result = subprocess.check_output('hello.bat')
print result

Now if you run it , the result will be a:

"This is a test bat"

This is easy. Let's look at another condition.

Condition 2: The exe file is in a different location from the python script that wants to run it.

Two diff folders with python script and bat file

No change in contents of hello.bat file. Some change in file.

import subprocess
result = subprocess.check_output('hello.bat', shell=True, cwd=r'D:\inchowar\Desktop\temp')
print result

The trick here is, cwd (current working directly) argument helps you automatically switch switch to that location specified before it tries to find the bat file . 

Otherwise you would have to do it yourself . Change directory before you run the bat file using os.chdir(r'D:\inchowar\Desktop\temp'), and then run the bat file, Obviously, this becomes tedious.

Note: When you are using the cwd argument, the bat file should not have a path before it. Only the name of bat file i.e hello.bat. NOT c:\Temp\hello.bat

As to when to use shell=True, I think this article has much better explanation than I can provide here.

Thanks for reading.

Total Pageviews