×

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

Convert string into int in Python

String A string is defined as a series of characters, special characters, and numbers. A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements...

2 minutes read.

Python ltrim() function

Python ltrim() function The ltrim() function in PHP removes whitespace or other predefined characters from the beginning or left side of a string. The related functions are as follows: rtrim() – This function is used to...

1 minute read.

Python setattr() function

Python setattr() function The setattr() function sets the value of the specified attribute of the specified object. Syntax setattr(object, name, value) Parameter object: This parameter represents any object. name: This parameter represents the name of the attribute you...

1 minute read.

Python round() function

Python round() function The round() function in Python returns a number rounded to ‘ndigits’ precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input. Syntax round(number[, ndigits]) Parameter Number: This parameter represents the...

1 minute read.

Front end in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

4 minutes read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

Check Letter in a String Python

Checking a specific letter or a character in a given string or a string which is taken as an input from the user is possible in Python in broadly three...

3 minutes read.

Python SQLite

SQLite It is an RDBMS (Relational Database Management System). It is an embedded, serverless, transactional SQL database engine. It is an open-source application. It is named SQLite because of its lightweight....

3 minutes read.

Importing Numpy in Pycharm

Numpy : Numpy is one of the important library in python. The abbreviation of numpy is “Numerical python” or “Numeric Python”. This library is mainly used to access arrays. Numpy was created...

5 minutes read.

How to convert Float to Int in Python?

A float value can be converted to an int via type conversion, an explicit method of transforming an operand to a certain type. But it must be noted that such...

3 minutes read.

Write a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

5 minutes read.

Python List append() Method

Python List append() Method The list.append() method in Python adds or appends an item to the end of the list. Syntax list.append(x) Parameter x: It is a required parameter that represents an element of any type (string, number,...

1 minute read.

How to learn python Online

Need to Learn a Programming Language 1. To get a high Paying job We know that Software Engineering is one of the top-paying professions in the world. The top criteria to be...

3 minutes read.

How To Print Colored Text in Python

Changing the colour of certain parts of a string when printing the output of a Python programme to the terminal may make it easier to read. We can approach this...

3 minutes read.

Python Sys Stdout

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

3 minutes read.

How to Download all Modules in Python

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.

Python List index() method

Python List index() method The list.index () method in Python returns the position at the first occurrence of the specified value. Syntax list.index(x[, start[, end]]) Parameter element – This parameter represents the element whose lowest index will be returned. start (Optional)...

2 minutes read.

Conditional Statements in python

In this article, we will learn about conditional statements and how to apply conditional statements in Python. A decision-making statement is another name for a conditional statement. Decision-making is an important...

5 minutes read.

How to Take Input in Python

How To Take Input In Python Python has various in-built functions that help in code redundancy. Let's discuss the usage of some functions- ascii() – it returns a readable representation of objects.format()...

4 minutes read.

Python sorted() function

Python sorted() function The sorted() function returns a sorted list of the specified iterable object. Syntax sorted(iterable, *, key=None, reverse=False) Parameter iterable: It is a required parameter that represents the sequence to sort, list, dictionary, tuple etc. key:...

1 minute read.