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)
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)
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!