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
- BASH (Bourne again shells) Scripting. The character for prompting of the bash scripting is a dollar symbol ($).
- 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:
- OS
- Platform
- Sub-processes
- Shutils
- Glob
- 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