Open In App
Related Articles

Python | os.system() method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

The OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent functionality.

os.system() method executes the command (a string) in a subshell. This method is implemented by calling the Standard C function system() and has the same limitations. If the command generates any output, it is sent to the interpreter’s standard output stream. Whenever this method is used then the respective shell of the Operating system is opened and the command is executed on it.

os.system() Syntax in Python

Syntax: os.system(command)

Parameter:

  • command: It is of string type that tells which command to execute.

Return Value: On Unix, the return value is the exit status of the process and on Windows, the return value is the value returned by the system shell after running command.

Interact with Operating System using Python Examples

There are various uses of os.system in the Python operating system or OS command. here we are discussing some general uses of os.system in the Python operating system or OS command those are following.

Get the Current Date

In this example, code imports the `os` module or uses the OS command and uses `os.system(‘date’)` to execute the ‘date’ command in a Windows operating system.

Python3

# importing os module
import os
 
# Command to execute
# Using Windows OS command
cmd = 'date'
 
# Using os.system() method
os.system(cmd)

                    

Output:

file-1

OS system Method to Run Notepad

In this example code imports the `os` module or use the OS command and uses `os.system(‘notepad’)` to execute the ‘notepad’ command on a Windows operating system, opening the Notepad application.

Python3

# importing os module 
import os 
   
# Command to execute
# Using Windows OS command
cmd = 'notepad'
   
# Using os.system() method
os.system(cmd)

                    

Output:

Annotation-2019-06-19-120037-1024x285

FAQ’s

What is the meaning of os.system in Python?

os.system in Python or OS in Python or Python operating system is a function that allows you to execute shell commands or system commands from within a Python script. It runs the specified command in the underlying operating system’s shell and returns the exit code of the command.

Is there a way to test the results of an os.system() command in Python?

Yes, the result of an `os.system()` command can be tested by examining the exit code. An exit code of 0 generally indicates success, while a non-zero code suggests an error or failure. You can capture the exit code using `os.system(‘command’)` and check it in your Python script for further validation or error handling.



Last Updated : 16 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads