Open In App

Executing Shell Commands with Python

Last Updated : 20 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.

subprocess.Popen()

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.

Python3




# Importing required module
import subprocess
 
# Using system() method to
# execute shell commands
subprocess.Popen('echo "Geeks 4 Geeks"', shell=True)


Output:

 

subprocess.run()

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.

Python3




# Importing required module
import subprocess
 
# Using system() method to
# execute shell commands
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. we are using the system() method to execute shell commands of echo.

Python3




# Importing required module
import os
 
os.system('echo "Geeks 4 Geeks"')


Output:

 

Example 2: 

Here, we are using the system() method to execute the PWD shell script using Python.

Python3




# Importing required module
import os
 
os.system('pwd')


Output: 

 

Example 3: 

Here. we are using the system() method to execute the cat shell script using Python.

Python3




# Importing required module
import os
 
os.system('cat')


Output: 

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads