How to Use Python commands Module

09/16/2021
Contents
In this article, you will learn how to use Python commands module.
Python commands Module
The commands module in Python is used to execute shell commands from within a Python script. Here’s how you can use it:
Import the commands module:
import commands
Use the getoutput() function to execute a shell command and get the output:
output = commands.getoutput('ls -l')
print(output)
In this example, the “ls -l” command is executed and the output is printed to the console.
You can also use the getstatusoutput() function to get both the status and output of a command:
status, output = commands.getstatusoutput('ls -l')
print(status)
print(output)
In this example, the “ls -l” command is executed and the status and output are printed to the console.
Note: The commands module is deprecated since Python 2.6 and has been removed in Python 3.0, use subprocess module instead for executing shell commands.