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

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.

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.

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,241FansLike
399FollowersFollow
16SubscribersSubscribe

LATEST ARTICLES

MUST READ

“I am because you are,” is the themed meaning behind the famed Ubuntu operating system. Moreover, this mindful phrase is practical because it continues to lure more individuals into the Ubuntu universe. Because great power beckons great responsibility, Ubuntu is stepping up. It realizes that different users will want to use the Ubuntu operating system software differently.
The Ubuntu Cinnamon Remix brings together Linux Mint's Cinnamon desktop with the Ubuntu Core. While some users are welcoming the new flavor of Ubuntu with open arms, others are scratching their heads, wondering where it fits in.

VIDEO: MX Linux 19 Features and Desktop Tour

MX Linux is a Linux distribution based on Debian stable and using core antiX components. The distributions MX Tools is very popular among users and combined with other several ready-to-use tools, it is great for users who prefer to tweak their distro to their liking. In this video, we will take you through the features tour showing casing MX Linux 19.

Ubuntu Cinnamon Remix Review

The Ubuntu Cinnamon Remix brings together Linux Mint's Cinnamon desktop with the Ubuntu Core. While some users are welcoming the new flavor of Ubuntu with open arms, others are scratching their heads, wondering where it fits in.

Top 6 Tiny Linux Distributions One Must Try

Linux is a versatile operating system. You can find different distros for different purposes and still be surprised by the functionality the distros have to offer without sacrificing too much. Tiny Linux Distributions are also like that. They are powerful yet compact and lets you run Linux operating systems on slow machines with minimal specs.

Top 10 Lightweight Linux Distros to Try in 2020

To get a taste of Linux, you don't always have to have a beast of a computer. We know that the latest version of Ubuntu and other such newer Linux distros can be a bit difficult to run on older systems. However, there are many operating systems in the world of Linux that are especially geared toward machines with low-end specifications.