How To Execute Shell Commands In Python?

Python provides different ways to execute shell commands inside the Python script. There are modules like os, subprocess, etc. in order to run shell commands or run processes which can be shell commands too. The shell commands can be used to accomplish specific tasks. Also, the executed shell commands can return different outputs which can be also used and interpreted in different ways.

Using os.system()

The os module provides different methods and functions to work with the operating system. The os.system() function is used to run shell commands in the current operating system. The os.system() function is very basic according to the other methods. The command we want to run is provided as string parameter to the os.system() function.

import os


Also parameters can be provided to the command for the function. The parameters are just added to the command string like a single string.

import os

os.system("ls -l /etc")


The subprocess module provides process-related functions and methods. The can be used to run a process which can be also a shell command. The shell command is provided as a list where parameters are provided as items in this list. The command output is returned with the run() which can be assigned into a variable.

import subprocess

output =['ls','-l'])


Using subprocess.Popen()

Another way to run a shell command is using the subprocess.Popen() function. The Popen() provides low-level access to the operating system by creating a new process with the provided parameters.

import subprocess

output = subprocess.Popen(['ls','-l'])


Leave a Comment