Python os.system() method is “used to execute the command (a string) in a subshell.” This method is a quick and easy-to-run shell command, but it’s less robust and flexible compared to more advanced methods like the subprocess module.
The command is executed in a subshell, which means that variables or state changes (like changing directories) in the command do not affect the parent Python process.
Unlike subprocess.Popen(), os.system() doesn’t provide a way to interact with the running process, such as piping data to it or reading its output directly.
Syntax
os.system(command)
Parameters
Name | Description |
command | It tells which command to execute. |
Return Value
It returns the exit status of the command.
Visual representation
Example 1: Basic usage
import os
cmd = 'date'
# Using os.system() method
os.system(cmd)
Output
Fri Jan 15 15:03:31 IST 2021
Example 2: Listing directory contents
import os
cmd = 'ls'
# Using os.system() method
os.system(cmd)
Output
Example 3: Running multiple commands
import os
cmd = 'mkdir new_folder && cd new_folder'
# Using os.system() method
os.system(cmd)
Output
Example 4: Handling command execution status
import os
status = os.system('cd ..')
if status == 0:
print("Command executed successfully")
else:
print("Command execution failed")
Output
Command executed successfully
Example 5: Executing the git command
import os
cmd = "git --version"
# Using os.system() method
os.system(cmd)
Output
git version 2.24.3 (Apple Git-128)
Notice that we are not printing the git version command output to the console; it’s being printed because the console is the standard output stream here.