Getting Realtime Output Using subprocess
Subprocess is a powerful module in Python used to execute other programs and interact with their input and output. However, users may encounter a scenario where they need to retrieve output from the executed program in real time, without any buffering.
Problem Description
The issue arises when using subprocess.Popen with stdout set as a pipe. The output from the wrapped program appears to be buffered, resulting in chunks of data rather than line-by-line delivery. Setting the bufsize parameter to 1 or 0 does not resolve the issue.
Solution: Iterative Reading from readline()
Despite the aforementioned subprocess behavior, the following code snippet effectively retrieves output in real time:
while True: line = p.stdout.readline() if not line: break ...
Using readline() instead of iterating over p.stdout directly bypasses the buffering issue and allows for real-time output retrieval.
Atas ialah kandungan terperinci Bagaimana untuk Mendapatkan Output Masa Nyata daripada Subprocess.Popen dalam Python?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!