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
Release: 2024-11-29 17:21:10
Original
338 people have browsed it

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()
Copy after login

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)
Copy after login

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!

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