Best Way To Execute Linux Commands using Python

Best Way To Execute Linux Commands Using Python3

Python is a trendy & modern programming language. Especially popular among beginners as it is easy to learn. Python is so powerful that we can use it to interact with the operating system. In Linux, python act as an alternative for bash command language for scripting. It comes preinstalled in most of the distributions as it is a dependency on many tools and software. And if not it is effortless to install.

In this tutorial, we will see how to run Linux commands using Python. The idea behind this is to automate tasks and save time. I am using Ubuntu for this tutorial.

Also read: Installing Latest Python on Debian/Ubuntu using Source


We will require a python environment. If you are using the latest distribution it is preinstalled. You can check using the following command.

❯ python3 --version

To install python run the following command –

❯ sudo apt install python3 -y

Additionally, if you have some knowledge of terminal & some Linux commands that will be great.

The OS module in Python python3

OS library provides operating system-based functions and allows us to interact with the operating system. The package comes with python installation, so no need to install it separately. The library is easy to use and contains both read and write operations.

Let’s write our first program and get system information –

Launch your favorite text editor (I am using gedit) –


Copy the below code and save the file –

import os


You can run the file like the below –



Get System Info Using Python
Get System Info

The uname() method returns information like name, release, and version of the current operating system, etc. This was just an overview of the OS module, now let’s run the terminal commands.


The os.system() method takes command as a string and executes it in a subshell. The limitations stand the same as the system() method in C language. The method is system dependent.

The code should be executed using the terminal as if you run the code in IDLE you get “0” as output and nothing really happens.

Os Module Python
No Output

Let’s run our very first command –

import os



Run Linux Comands Using Python
list files and folders

The ls command is used to list items in the respective directory.

Accept Linux Command As User Input

Let’s take input from users and then concatenate it with our command. For eg: Creating folders while taking folder names from the user.


import os
name = input("Enter a folder name : ")
os.system('mkdir ' + name)


Create Folders Using Python
Creating Folders

Complete Code for Executing Linux Commands Using Python

I have developed a simple script to give you guys an idea of how you can use python to make your job easy.

import os

while (True):
    print("1) List Directories")
    print("2) Create a file")
    print("3) Create a directory/folder")
    print("4) Ping a server")
    print("5) Neofetch")
    print("6) Check Python Version")
    print("7) Check Java Version")
    print("8) Exit")

    ch = int(input("Enter Your Choice : "))

    if ch == 1:
    elif ch == 2:
        f_name = input("Enter file name : ")
        e_name = input("Enter file extension : ")

        os.system('touch ' + f_name + '.' + e_name)
    elif ch == 3:
        name = input("Enter folder name : ")
        os.system('mkdir ' + name)

    elif ch == 4:
        s = input("Enter address(Press enter for default - : ")
        p = input("Enter number of packer(press enter for default - 10 : )")
        o = input("Do you want the output in a txt file -- y | n -- :")

        # p = int(p)

        if (s == ''):
            s = ''
        if (p == ''):
            p = '10'

        if (o == 'y'):
            os.system('ping ' + s + ' -c ' + p + ' > ping-output.txt')
            os.system('ping ' + s + ' -c ' + p)

    elif ch == 5:

    elif ch == 6:
        os.system('python --version')

    elif ch == 7:
        os.system('java --version')

    elif ch == 8:
        print("Invalid Choice")

This will show a menu to the user and the user has to choose any one option. As the script is in a while loop the menu will be presented to the user continuously. You can add more options to the menu.


The Script Of Everything
The Script Of Everything

Wrapping Up!

This was just a small part of the OS module. It has many more features and methods. You can set the path of the scripts you have developed in the shell configuration file. This will allow you to run the scripts from anywhere. Also, create cron jobs to execute automatically from time to time. Hope this article helped you in some way.

Articles You Might Be Interested In