Home > Backend Development > Python Tutorial > How Can I Discreetly Handle the Output of os.system in Python?

How Can I Discreetly Handle the Output of os.system in Python?

Patricia Arquette
Release: 2024-11-28 06:34:13
Original
477 people have browsed it

How Can I Discreetly Handle the Output of os.system in Python?

Handle Output of os.system Discreetly

When executing commands using os.system, the output is typically displayed on the screen. However, there are situations where you want to assign the output to a variable and prevent its appearance on the screen.

The provided code demonstrates this issue:

var = os.system("cat /etc/services")
print(var)
Copy after login

Instead of capturing the command output, var will contain 0, indicating the successful execution of the command. To resolve this, consider using popen:

var = os.popen('cat /etc/services').read()
Copy after login

As the documentation for Python 3.6 suggests, subprocess.Popen provides a more robust solution for managing subprocesses.

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

Using subprocess, you can capture both the standard output and error stream, as shown in the code above.

The above is the detailed content of How Can I Discreetly Handle the Output of os.system in Python?. 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