Python os.system: The Complete Guide

Python OS module presents a way of using operating system-dependent functionality. The OS module’s functions allow you to interact with the underlying operating system that Python is running on.

Python os.system()

Python os.system() is a built-in method that executes the command in the subshell. The os.system() method takes a command as an argument and executes it. The os.system() is implemented by calling the Standard C function system() and has the same limitations.

The os.system() function is simple to use and interpret as an input of the function. It is the same command you would use in a shell.

Syntax

os.system(command)

Parameters

The command is of string type that tells which command to execute.

Return Value

It is based on the Operating system you are using. If you are using UNIX, it will return the process’s exit status, and if you are using Windows, then the return value is the value returned by the system shell after running the command.

The os.system() function will execute the shell command, and the result will be printed to the standard output, but the output that the function returns is a return value.

Example

We will use the os.system() method to get the computer’s current date.

import os

cmd = 'date'

# Using os.system() method
os.system(cmd)

Output

Fri Jan 15 15:03:31 IST 2021

Let’s try to know the version of git using the system command git –version.

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.

That is it for the Python os.system() method.

See also

Python os.walk()

Python os.path.dirname()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.