Home > Backend Development > Python Tutorial > How to Capture and Assign System Command Output to a Variable in Python without Screen Display?

How to Capture and Assign System Command Output to a Variable in Python without Screen Display?

Linda Hamilton
Release: 2024-12-17 18:49:20
Original
368 people have browsed it

How to Capture and Assign System Command Output to a Variable in Python without Screen Display?

Assigning Output of os.system to a Variable while Suppressing On-Screen Display

In Python, os.system is used to execute a system command and returns a value indicating the command's exit status. However, the command's output is typically displayed on the screen. This may not be desirable in certain situations.

To assign the command output to a variable and prevent it from being displayed on the screen, you can use the os.popen() function instead of os.system. os.popen() returns a pipe object that you can use to read the command's output.

import os

# Use os.popen to capture the output of the command
popen_object = os.popen('cat /etc/services')

# Read the output from the pipe object
output = popen_object.read()

# Print the output, which will not be displayed on the screen
print(output)
Copy after login

Alternatively, you can use the more powerful subprocess.Popen class to manage and communicate with subprocesses. Here's how you would achieve the same result using subprocess.Popen:

import subprocess

# Create a subprocess object
proc = subprocess.Popen(['cat', '/etc/services'], stdout=subprocess.PIPE)

# Communicate with the subprocess and retrieve its output
output, _ = proc.communicate()

# Print the output, which will not be displayed on the screen
print(output)
Copy after login

The above is the detailed content of How to Capture and Assign System Command Output to a Variable in Python without Screen Display?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template