How to Execute a Command Prompt Command From Python
In this tutorial, you will run a Windows system command using Python.
TLDR solution
cmd.py
import subprocess
cmd = "your cmd command"
subprocess.run(cmd, shell=True)
Example 1: Run a cmd Command
Let's say, you want to create a script that creates a folder named Test on your desktop.
The script might look like this:
mkdir.py
import os
import subprocess
path = os.path.expanduser("~/Desktop") + "/Test"
cmd = "mkdir path"
subprocess.run(cmd, shell=True)
After you run this code, you will find a newly created Test folder on your desktop.
Example 2: Run a cmd Command and Get the Output
Let's say, you want to create a script that creates gets the version number of your system's Windows. The script might look like this:
get_win_version.py
import subprocess
cmd = "ver"
output = subprocess.check_output(cmd, shell=True).decode("utf-8")
print(output)
After you run this code, the version number of your Windows will be printed to your shell.
That's it! You just learned how to execute a Windows system command using Python.