Print Output from Os.System in Python
Last Updated :
24 Apr, 2025
In Python, the os.system()
function is often used to execute shell commands from within a script. However, capturing and printing the output of these commands can be a bit tricky. This article will guide you through the process of executing a command using os.system()
and printing the resulting values.
How to Print Value that Comes from Os.System in Python?
Below is the step-by-step guide of How To Print Value That Comes From Os. System in Python:
Step 1: Import the os Module
Before using the os.system()
function, you need to import the os
module in your Python script. This module provides a way to interact with the operating system, including executing shell commands.
import os
Step 2: Use os. system() to Execute Command
The os.system()
function takes a string argument, which is the shell command you want to execute. For example, let's execute the ls
command in a Unix-like system to list the files in the current directory:
os.system("ls")
This command will print the output directly to the console.
Step 3: Capture the Output
To capture the output of the command and print it in your Python script, you can use the subprocess
module. The subprocess
module provides more control and flexibility over executing and interacting with external processes. In this example, the subprocess.check_output()
function is used to capture the output of the command. The text=True
argument ensures that the result is returned as a string.
Python3
import subprocess
command = "ls"
result = subprocess.check_output(command, shell=True, text=True)
print(result)