Executing Shell Commands with Python
This article starts with a basic introduction to Python shell commands and why one should use them. It also describes the three primary ways to run Python shell commands.
What is a shell in the os?
In programming, the shell is a software interface for accessing the functionality of the operating system. Shells in the operating system can be either a CLI (Command Line Interface) or a GUI (Graphical User Interface) based on the functionality and basic operation of the device.
Executing Shell Commands with Python using the subprocess module
The Python subprocess module can be used to run new programs or applications. Getting the input/output/error pipes and exit codes of different commands is also helpful.
Here. we are using the subprocess.Popen() method to execute the echo shell script using Python. You can give more arguments to the Popen function Object() , like shell=True, which will make the command run in a separate shell.
Here. we are using the system() method to execute the pwd shell script using Python. run() is more flexible and quicker approach to run shell scripts, utilise the Popen function.
Executing Shell Commands with Python using the os module
The os module in Python includes functionality to communicate with the operating system. It is one of the standard utility modules of Python. It also offers a convenient way to use operating system-dependent features, shell commands can be executed using the system() method in the os module.
Here. we are using the system() method to execute shell commands of echo.
Here, we are using the system() method to execute the PWD shell script using Python.
Here. we are using the system() method to execute the cat shell script using Python.
Please Login to comment...