Home >Backend Development >Python Tutorial >How to Capture Command Output from `os.system` in Python Without Displaying it on the Screen?

How to Capture Command Output from `os.system` in Python Without Displaying it on the Screen?

Linda Hamilton
Linda HamiltonOriginal
2024-11-29 17:21:10345browse

How to Capture Command Output from `os.system` in Python Without Displaying it on the Screen?

How to Capture Command Output from os.system Without Screen Display

When using os.system to execute commands, the output is typically displayed on the screen. However, you may desire to capture the command's output and store it in a variable for further processing.

To address this, you can utilize os.popen instead:

output = os.popen('cat /etc/services').read()

As stated in the Python 3.6 documentation:

"This is implemented using subprocess.Popen; see that class's documentation for more powerful ways to manage and communicate with subprocesses."

For more control over the subprocess, consider using subprocess directly:

import subprocess

proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print("program output:", out)

The above is the detailed content of How to Capture Command Output from `os.system` in Python Without Displaying it on the Screen?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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