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.

-Advertisement-

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().

-Advertisement-

Let’s save our Python file as usingos.py.

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

import os
os.system('ls')

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.

-Advertisement-
python usingos.py

os-example-ls
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.

-Advertisement-

Let’s save our new Python script as savingvalue.py

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

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

popen-python
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 subproc.py.

Inside it, you need to use the following code.

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

subproc-example-1
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 subprocess.run() 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:

["ls","-l"]

Conclusion

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.

-Advertisement-
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!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

STAY CONNECTED

23,641FansLike
362FollowersFollow
16SubscribersSubscribe

LATEST ARTICLES

Top 20 Git Commands with Practical Examples

If you are here reading this post, there is a high probability that you have heard or interacted with Github, and you now want to learn Git. Before we continue with showing you some of the cool Git commands, let's understand the difference between Git and GitHub.

Top 10 New Features in Linux Kernel 5.7

Linus Torvalds has announced the release of Linux Kernel 5.7 after seven weeks of development. The release announcement comes as a piece of exciting news as it brings a host of new features for the hardware manufacturers as well as the developers.

How to install CMake on Ubuntu

CMake is a cross-platform free and open-source software tool designed to build, test, and package the software. CMake uses a simple platform and compiler-independent configuration files to control the software compilation process.

How to install Lightworks on Ubuntu

Even though Linux may not get a native installer of video editing software like Adobe Premiere or Final Cut Pro, that doesn't mean there are no industry standards tools available. Lightworks is non-linear editing (NLE) video mastering app for Windows, Linux, and macOS. Installing it on Ubuntu is simple due to deb package availability.

How to install DaVinci Resolve on Fedora

Davinci Resolve is a professional application used for color correction, video editing, visual effects, and motion graphics. It is one of the extensively used software by movie industries located in Hollywood.

The 10 Best Programming Languages for Hacking

One of the significant entities we have in Cyber Security is Ethical Hacking (ETH). It is the process of detecting and finding flaws or vulnerabilities in a system that a hacker would exploit.

MUST READ

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.

Installing multiple Linux distros on a USB drive

A bootable Linux USB drive, which also referred to as a Live USB drive, is a drive containing files that enable a computer to boot into a specific Linux distro. It is most commonly used to test-drive various Linux distros before installing on the computer for use as a daily driver.

Installing an updatable Manjaro Linux on a USB Flash Drive

In this tutorial, we will show step by step how to install a Manjaro on a USB flash. For those new to this distro, it is a light-weight distro that is based on Arch Linux. Arch Linux is known for its simplistic approach and is typically made for Linux pros, but Manjaro bridges the gap between user-friendliness and rock-solid performance.

VIDEO: Linux Lite 4.8 Features and Desktop Tour

Linux Lite eases Windows 7 users transition to Linux much more comfortable by offering simple software like Team Viewer, VLC, Firefox, TimeShift backup utility, and a full Microsoft Office compatible office suite in LibreOffice.

The 6 Best Download Managers for Fedora

It is a well-known fact that using download managers can help improve download speeds as compared to web browsers. Apart from the inbuilt download manager wget on Fedora, just as on any distribution that is based on GNU/Linux package, there are more options to explore.