×

Executing Shell Commands in Python

This tutorial aims to make us understand what a Shell is, what is the importance of a Shell, what are Shell commands in Python, and how can we execute the Shell commands in Python in detail. We will also see how we can write some basic Shell commands in Python programming language.

What is a Shell?

From a Programming Languages point of view, a shell is a software interface where it is mainly used for the functional testing of an operating system, and it can either be used in GUI (Graphical User Interface) or in CLI (Command Line Interface).

To be more precise, a Shell can be understood as a computer program that the human user uses directly to work with the operating system, either Windows, Linux or even Unix, to control the computer using the commands, not by selecting the pre-defined options as we generally do in Windows operating system for an instance creating a dictionary which will be equals to creating a directory using commands in Shell scripting using Python Programming here. In most cases, the Shell scripting is carried out using a Command Line Interface (CLI), not by a Graphical User Interface (GUI).

Importance of Shell Scripting?

A Shell Script is useful when we are creating the command sequences where the user has to input it repeatedly, which will save a lot of time for the users. In a similar way, the Shell Scripting can contain parameters, comments, sub commands and commands in the shell script by entering the file name or directory name on the command line interface.

How does the Shell Scripting work?

The Shell Scripting contains the ASCII value texting into it. These are written using a Text editor, word processor, or even using Graphical User Interface (GUI). The commands that we write in the command-line interface using the editor are written further written down in any one of the in-built programming languages, which are further interpreted by the shell itself. Some of the various functionalities that the shell can perform include variables if or else or then statements, looping, arrays and also some shortcuts in it.

Types of Shells that we generally use

  1. BASH (Bourne again shells) Scripting. The character for prompting of the bash scripting is a dollar symbol ($).
  2. C-shell scripting. The character for prompting of the C-shells scripting is a percentage symbol (%).

Modules in Python:

Following are the various modules in Python that the shell scripting can work:

  1. OS
  2. Platform
  3. Sub-processes
  4. Shutils
  5. Glob
  6. sys

Shell Commands in Python

See the below code or scripting commands for printing a few statements using the shell scripting

Code:

import os


os. system("echo Hello from the other side of the world to you people!")

Output:

Hello from the other side of the world to you people!

Code:

#First statement is Importing the required module
import os


#We will be Using the system() method to
# execute shell commands
os.system('echo "JAVA T POINT"')

Output:

JAVA T POINT


Code to create a new file called codes.py
import os


home_dir = os.system("cd ~")
print("`cd ~` ran with exit code %d" % home_dir)
unknown_dir = os.system("cd doesnotexist")
print("`cd doesnotexis` ran with exit code %d" % unknown_dir)

Output:

$ python3 codes.py

Using the Subprocess Module

The subprocess module provides us with powerful facilities to spawn new processes and also to retrieve the results. Using the sub-processes module is very much preferable for the function.

Code:

import subprocess
process = subprocess.Popen(['echo', 'More output in the window'],
                     stdout=subprocess.PIPE, 
                     stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
stdout, stderr

Output:

(b'More output in the window\n', b'')

OS Module:

Some of the basic shell commands using the OS module using Python Programming Language. This is one of the native approaches to interacting with the operating system to run the shell command.

Before executing any command, we have to create any file; for instance, we are creating a sample file named os_sample_file.py before executing the below shell commands.

Code:

import os


os.system('date')

Output

$ python shell_command.py
WED July 13 12:33:23 GMT 2022

Code:

import os
output = os.popen('date')
type(output)
<class 'os._wrap_close'>
print(output.__dict__)
{'_stream': <_io.TextIOWrapper name=3 encoding='UTF-8'>, '_proc': }         
output.read()
' WED July 13 12:33:23 GMT 2022\n'

Output Window:

output.read()


import os
print(os.popen('date').read())
WED July 13 12:33:23 GMT 2022

Related Topics

Conditional Expressions in Python

In Python conditional expression are sometimes referred to operator called as ternary operator. Not only Python supports ternary operator but many other programming languages supports it. Ternary operator are the...

2 minutes read.

How to slice a list in python

When working with lists, we face situations where we may need a part of the list from one index to the other. Slicing is one of the simpler ways to...

5 minutes read.

Sentence to python vector

Conversion of a Sentence to Vector in Python Before starting the tutorial, let’s just recap about the vector and the respective package that has to be imported in Python. Python Vector: Putting simply,...

3 minutes read.

Android apps for coding in python

Nowadays, it is the generation of smartphones. The world can be seen and acknowledged with a single click on your mobile phone. Everyone uses mobile phones to do any work,...

9 minutes read.

Socket Programming in Python

Socket Programming in Python In this tutorial, we will discuss network programming using Python programming language. We will explore all basic concept of network with Python script. Network Services in Python Python has...

9 minutes read.

Python List Size

Introduction The list data type in Python is an ordered, flexible collection. A list may also contain duplicate entries. To get the size of any object, use the len() function in...

6 minutes read.

Check if a String is Empty in Python

The string is one of the data types of Python. This data type stores all kinds of data but all the characters must be enclosed using double quotes (""). In...

5 minutes read.

Python Os sep

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Sklearn in Python

Scikit-learn or sklearn is a machine learning library used in Python that provides many unsupervised and supervised learning tools and algorithms. David Cournapeau first created it as a 2007 Google...

7 minutes read.

Sys Module in Python

What are Modules? The Modules are the kind of files that contain Python statements and definitions. The module is known by the name of the file followed by the suffix “.py”....

5 minutes read.

apply() function in python

Pandas: Pandas is a library in python. It is an open source package in python. Pandas in python are used for data cleaning and data analysis. Data frame mainly consists of...

3 minutes read.

Pltpcolor in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python for loop

 Python for loop A for loop in Python executes a block of code for a specified number of times, based on a given sequence. The for loop in Python is different than any other...

3 minutes read.

Gethostbyname() function in Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python | Read csv using pandas.read_csv()

Python is an excellent language for performing information analysis, owing to the fantastic biological system of information-driven python packages. Pandas is one of those packages that make taking in and...

4 minutes read.

Python System Requirements

Introduction As we know, Python is a popular programming language usually used to write scripts for operating systems. It’s handy adequate for utilizing in web development and application design. In this article,...

2 minutes read.

Python Set symmetric_difference() method

Python Set symmetric_difference() method The set.symmetric_difference() method returns a new set, which is the symmetric difference of two sets. The returned set contains only the unique items and, hence, deleting the common elements of...

2 minutes read.

iobase Python

All I/O flow classes derive from this conceptual base class. Derived classes will have to execute several of the class's abstract data types. The loop method is supported by all members of...

4 minutes read.

What Does the Percent Sign (%) Mean in Python?

In python, the percent sign is called modulo operator " %, " which returns the rest of partitioning the left-hand operand by the right-hand operand. Example: value1 = 8 value2 = 2 remainder =...

4 minutes read.

Convert int to Float in Python using Pandas

Introduction We have already learnt about how to convert float variables to int. Now let us know how to convert int variables to float So let us create another Dataset on which...

2 minutes read.