Execute Shell Command and Get Output in Python

Salman Mehmood Oct 10, 2023
  1. Execute CMD Commands From a Python Script and Get Output Using os.system()
  2. Execute CMD Commands From a Python Script and Get Output Using the Subprocess Module
Execute Shell Command and Get Output in Python

In this article, we will learn how to execute cmd commands from a Python script with the help of os.system(). We will also learn how we can execute cmd commands from the script in an easier way with the help of the subprocess module in Python.

Execute CMD Commands From a Python Script and Get Output Using os.system()

We execute terminal commands in command prompt or any other terminal for different purposes. But, sometimes, running a particular command inside the script is necessary.

We will see how we can execute them directly inside the Python script. It is handy when we work with server configuration.

First, let us show you some commands that work in the terminal, such as dir, cd, or md.

Terminal Commands in Command Prompt

Now, we will see how we can include the same ones in the Python script. To do that, we will import a module called os.

The os module will help us to interact with our operating system. The os module has extensive support for operating system tasks such as files and folder management.

Let’s jump into the code. The system() is a method that executes the command in the like shell, so if we give it any command, it will go ahead and execute them the way we would execute them in the terminal.

The system function can also execute a bunch of commands. It executes every command that you can run in the terminal.

We will use the try block, and inside this block, we will use the system() method, which will help us to interact with the operating system using the terminal. If the try block does not execute the specified command, we will go onto the except block.

Inside the system() method, we have to pass our commands, but the command type is cmd. For that, we use /k, and inside a single or double quotation, we have to type our command.

import os

    os.system('cmd /k "date"')
    print("Could not execute command")

Let’s run and see whether this gives us the exact output.

The current date is: 24/08/2022
Enter the new date: (dd-mm-yy)

We can see the output is the same as the command prompt gives.

There are lots of commands you can execute. You can open Notepad or Calculator, or you can see your system information and much more.

Open Applications and Show System Info From Python Script

If you want to get the content of what the command returns, you can get it using the popen() function of the os module. Inside this function, we can pass the command and use the readlines() method to get its content.

We can use many methods to get clean data. It depends on you.

import os

DATA = os.popen("help").readlines()[5].strip("\n")

Get the Content the Command Returns

We can use these commands anywhere, like class, loops, and function. This will properly work as it does without wrapping it in a function.

import os

def CMD_Com():
    DATA = os.popen("help").readlines()[5].strip("\n")



CACLS          Displays or modifies access control lists (ACLs) of files.

Execute CMD Commands From a Python Script and Get Output Using the Subprocess Module

Interacting with subprocesses is an essential skill to have. Using the os module is not recommended to execute a terminal command inside the Python script.

Using os.system() to execute the terminal command is a very simplified way of running a command in Python.

The os.system() has limited functionality; the proper way is to use a module called subprocess, which makes it not too challenging to execute terminal commands. Using the subprocess module, we can run all the operating system commands on which we are currently working.

This is how we can run all existing commands in an operating system, like opening Notepad or checking the current working directory, or any other operation we can execute using the subprocess module.

import subprocess

# subprocess.Popen('notepad')
# subprocess.Popen('systeminfo')
subprocess.Popen("dir", shell=True)


 Directory of C:\Users\Dell\Downloads\demo

24/08/2022  07:01 pm    <DIR>          .
24/08/2022  07:01 pm    <DIR>          ..
25/08/2022  01:47 am               460 demo.py
               1 File(s)            460 bytes
               2 Dir(s)  32,532,512,768 bytes free

You can learn more about the subprocess module from here.

Salman Mehmood avatar Salman Mehmood avatar

Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.