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
Patricia ArquetteOriginal
2024-11-28 06:34:13438browse

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)

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

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)

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!

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