Did you know that a Python script can run other programs?
That’s right. Whether you’re building a bot, an automation, or a script that simply relies on another program to get the job done, there’s a way to get things done, and do them properly, in Python. This tutorial will show you how.
Opening Other Programs
The recommended way for opening other programs in Python is using the subprocesses
module, which lets you spawn new processes, connect to their input/output/error pipes, and obtain their returns.
You could also use the os.system
interface to do this. However, it will pause the script’s execution, run the other program, and wait for it to complete before resuming the script. Whereas, if you open the other program using the subprocess
module, it will run in parallel with the script, allowing you to do more.
To launch the other program, pass its absolute page path as an argument to the Popen()
constructor. For example, the code snippet below runs Command Prompt on a Windows computer:
# Import the subprocess module
import subprocess
# Open Command Prompt on Windows
process = subprocess.Popen(["C:\WINDOWS\system32\cmd.exe"])
Locating Other Programs
Of course, to open another program, you first need to know where it is. And there may be situations in which you know which program you want to open, but you don’t know where on the user’s system it is.
In a thread on the topic, one StackOverflow user proposes the following approach, with the case in point being finding the location of Google Chrome:
# Import the windows registry
import winreg
# Import regular expressions (RegEx)
import re
lookup = winreg.QueryValueEx(winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "ChromeHTML\\shell\open\\command", 0, winreg.KEY_READ), "")[0]
location = re.search("\"(.*?)\"", lookup).group(1)
Here’s what the code would look like if you were to open Mozilla Firefox:
# Import the windows registry
import winreg
# Import regular expressions (RegEx)
import re
lookup = winreg.QueryValueEx(winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "FirefoxHTML\\shell\open\\command", 0, winreg.KEY_READ), "")[0]
location = re.search("\"(.*?)\"", lookup).group(1)
Once you’ve found the absolute path of the program you want to open, you can pass it as a parameter to the Popen()
constructor.
In Summary
The best way to open another program in Python is using the Popen()
constructor of the subprocesses
module. This will keep your parent script and the child program running in parallel and allows you to do more compared to other methods, which temporarily pause the script’s execution until the program is done running.