How to execute a Shell command with Python

Python's usefulness comes from its ease of usage and its standard library. With it, you can successfully execute shell commands, and that's the topic of our today's tutorial.

Python is one of the popular programming languages out there. If you are using Linux, then learning it helps you in automating workflows and scripts.

Python’s usefulness comes from its ease of usage and its standard library. With it, you can successfully execute shell commands, and that’s the topic of our today’s tutorial.

In most cases, you might have used to use a bash or batch file to execute your commands, but you shall be able to do it in Python too. We shall guide you on how to run the shell command with Python.

Executing the Shell commands with Python

1. OS Module

One of the easiest and safest way to run the shell command via Python is to use os.system().

Let’s save our Python file as

Below is the code that you need to use it within your data.

import os

In the Python file, we first import the os module and then call the system method() to pass the command that you want to run. As you can see, we ran the “ls” command in it. If you run the python file, then you will get the following output.


Running ls command using Python os module

However, using the os module is very limited. First of all, you will not be able to save the output to a variable.

To save the output, you need to use a different function with the os module. It is popen(). It simply opens up a pipe to and from a command line. By doing so, the Python stream can be accessed, and hence the values can be stored in a variable.

Let’s save our new Python script as

Inside it, you need to type in the following code.

import os
stream = os.popen('eThe value is now returned')
output =
print (output)

Using popen

2. Subprocess Module

Finally, we will take a look at the subprocess module. If you are serious about running shell commands using Python, then you should use the subprocess method. You need your Python version at 3.5 or higher to use the subprocess module.

But why should you do so? It is because of the fact subprocess comes with excellent features that work well when working with shell commands in Python. For instance, you will be able to store the results in variables and also start a new process without trying to re-invent the wheel.

Let’s take a look at an example to get a better understanding. We name our file for this example as

Inside it, you need to use the following code.

import subprocess
list_file_names =['ls'])
print ("Here are the files %d" %list_file_names.returncode)

Shows how the subprocess module works

The first line of the code imports the subprocess module. Once done, we now create a new variable named “list_file_names” and then use the function. It takes input in a list. As you can see, we put in a Linux command, ls that lists files and folder(s).

Lastly, we print the variable with a return code.

To pass an argument to the command, you need to pass the argument as another element in the list. So, if you want to pass the “-l” argument to “ls,” then the list will as below:



It brings us to the completion of our tutorial on how to execute the Shell command with Python using the os and subprocess modules. While the os module is more of a straight-forward solution to run a shell command, the subprocess module has more powerful features for triggering new processes and extracting the output. What more ways do you use Python? Share your tricks with our readers in the comments below.

Divya Kiran Kumar
I'm the Editor of FOSS Linux. I worked as a Software Engineer before taking up blogging as my full-time job. I enjoy using Linux, and can't imagine anything else for my PC. Apart from writing for FOSS Linux, I enjoy reading non-fictional books. Sapiens was my favorite last read. I hope you enjoy reading and using this blog to enhance your Linux experience! Have a great day ahead!


Please enter your comment!
Please enter your name here




How to install CouchPotato on Ubuntu

Downloading movies and copying them over to your home server can get frustrating, especially if you are doing it daily! What if you have an option to download videos automatically, quickly, and above all with excellent quality. CouchPotato allows you to download movies easily once they are available and released automatically.

Top 20 Rsync Examples in Linux

The Rsync (remote sync) command is a Linux/Unix utility used to synchronize and copy files and directories either locally or remotely. Most Linux geeks use Rsync to mirror, backup or migrate data across folders, across disks and networks. One notable feature with the Rsync command is that it uses the "delta transfer algorithm."

Setting up NFS Server on Ubuntu Server

We have put together a detailed step-by-step tutorial that will guide you on how to install and set up NFS Server on Ubuntu so you too can start sharing data with other client systems. It is divided into sections, the first part discussing how to set up the host server and the second part showing you how to set up the client-side. For this tutorial, we will be using Ubuntu 20.04 LTS.

Crontab in Linux Explained With Examples

Crontab is the Linux equivalent of the Window's Task Scheduler. It can help you set up a task to run automatically at a regular...

The 10 Best Linux Server Distros For Home And Businesses

By the year 2020, it is estimated that there are close to 600 Linux distributions in the market. It includes both servers and Desktop versions; therefore, if you are looking for lightweight Linux distribution for your old PC or a reliable desktop version for employees in your organization, you may be overwhelmed with the number of choices for finding one for your use.

How to list the installed Packages on Ubuntu

It is only natural to start installing more and more software on your Ubuntu PC once you start using it. Similarly, it is also natural to lose track of the different packages that you have installed on your system. Eventually, you may be overwhelmed with the number of packages in your system and with the ones you hardly used.


Linux is growing faster than ever. As per the latest report, there is a drop in the Windows 10 market share for the first time, and Linux's market share has improved to 2.87% this month. Most of the features in the list were rolled out in the Pop OS 20.04. Let's a detailed look into the new features, how to upgrade, and a ride through video.
Elementary OS 5.1 Hera has received a point release with a handful of new features and bug fixes, and we will be reviewing the significant changes in this article. For those new to elementary OS, this Ubuntu-based Linux distribution uses their inhouse built Pantheon desktop environment and AppCenter.

Top 20 must-have apps for your Ubuntu PC

OK, this one is going to be a long one, so grab a cup of coffee and scroll through the best apps that we think are must-have for your Ubuntu PC. We have hand-picked each one of these considering the most common categories that suit an average Linux user.

10 Best Screen Capturing Software for Linux

Do you want to make a video tutorial for YouTube or show-off your epic victory royale to your friends? Look no further — as we have compiled the 10 Best Screen Capturing Software for Linux. Whether you need to record your desktop screen or take a simple screenshot, FOSSLinux has got your back.

How to clone hard disk on Linux using Clonezilla

Disk cloning refers to the process of copying data from one disk to another, thus creating a one-to-one copy of the drive. Technically, this process is possible using the copy-and-paste method.

6 Best Linux Distros for Laptops

Whether buying a Linux pre-installed laptop or selecting a Linux distro for your existing laptop, there are many things to consider. Let's take you through some of the best Linux distros that are optimized for Laptops in this 2019 edition of the article. Read on.