Home > Backend Development > Python Tutorial > How Can I Capture os.system Output in a Python Variable Without Displaying it on the Screen?

How Can I Capture os.system Output in a Python Variable Without Displaying it on the Screen?

Barbara Streisand
Release: 2024-12-06 09:25:11
Original
309 people have browsed it

How Can I Capture os.system Output in a Python Variable Without Displaying it on the Screen?

Assigning os.system Output to a Variable Without Screen Display

In Python, the os.system function executes system commands, returning an exit code. However, printing the output to the screen can be undesirable. This article explores solutions to capturing the output in a variable while suppressing on-screen display.

Solution 1: Using os.popen

According to a previous inquiry, os.popen offers a viable option:

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

As specified in the Python 3.6 documentation, os.popen utilizes subprocess.Popen, providing more robust capabilities for managing and communicating with subprocesses.

Solution 2: Using subprocess.Popen

For direct use of subprocess, the following code demonstrates the capture output technique:

import subprocess

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

By setting stdout=subprocess.PIPE, the output is captured, which can then be accessed and printed as desired.

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

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