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
os.system("ls")
Also parameters can be provided to the command for the os.systems() function. The parameters are just added to the command string like a single string.
import os
os.system("ls -l /etc")
Using subprocess.run()
The subprocess
module provides process-related functions and methods. The subprocess.run() 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 = subprocess.run(['ls','-l'])
print(output)
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'])
print(output)