Home >Backend Development >Python Tutorial >How Can I Capture os.system Output in a Python Variable Without Displaying it on the Screen?
In Python, the os.system function executes system commands, returning an exit code. However, printing the output to the screen can be undesirable. This article explores solutions to capturing the output in a variable while suppressing on-screen display.
According to a previous inquiry, os.popen offers a viable option:
os.popen('cat /etc/services').read()
As specified in the Python 3.6 documentation, os.popen utilizes subprocess.Popen, providing more robust capabilities for managing and communicating with subprocesses.
For direct use of subprocess, the following code demonstrates the capture output technique:
import subprocess proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() print("program output:", out)
By setting stdout=subprocess.PIPE, the output is captured, which can then be accessed and printed as desired.
The above is the detailed content of How Can I Capture os.system Output in a Python Variable Without Displaying it on the Screen?. For more information, please follow other related articles on the PHP Chinese website!