Home >Backend Development >Python Tutorial >How Can I Discreetly Handle the Output of os.system in Python?
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!