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.
- os.system()
- subprocess.run()
- subprocess.Popen()
Shell in 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 using 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.
1. subprocess.Popen()
Example: Here the subprocess.Popen() method is used 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.
import subprocess
subprocess.Popen('echo "Geeks 4 Geeks"', shell=True)
Output

2. subprocess.run()
Example: Here the system() method is used to execute the pwd shell script using Python. run() is more flexible and quicker approach to run shell scripts, utilise the Popen function.
import subprocess
subprocess.run(["powershell", "pwd"], shell=True)
Output

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.
Example 1: Here the system() method is used to execute shell commands of echo.
import os
os.system('echo "Geeks 4 Geeks"')
Output

Example 2: Here, the system() method is used to execute the PWD shell script using Python.
import os
os.system('pwd')
Output

Example 3: Here, the system() method is used to execute the cat shell script using Python.
import os
os.system('cat data.txt')
Output
