You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中使用subprocess.check_output执行netstat时如何获取实时输出?

Solution for Real-Time netstat Output with subprocess

Hey there! The problem with subprocess.check_output() is that it waits for your command to finish entirely before returning all output at once—so real-time streaming just isn't possible with it. To get output as it's generated, you'll need to use subprocess.Popen() directly, which gives you low-level access to the process's streams.

Here's a modified version of your code that streams netstat output in real-time, using poll() to track the process's status:

import subprocess

cmd = 'netstat -nlpt'
# Launch the process and pipe its stdout/stderr
process = subprocess.Popen(
    cmd,
    shell=True,
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    text=True  # Returns strings instead of bytes (no need for decode())
)

# Stream output line by line as it's generated
while True:
    # Read a single line from stdout
    line = process.stdout.readline()
    if not line:
        # If no line is returned, check if the process has exited
        if process.poll() is not None:
            break
        continue
    # Print the line immediately (strip removes extra newlines)
    print(line.strip())

# Ensure the process fully exits and check return code
return_code = process.wait()
if return_code != 0:
    print(f"Command failed with exit code {return_code}")

Key Details:

  • subprocess.Popen(): Unlike check_output(), this doesn't block until the process ends—it starts the process and lets you interact with it while it runs.
  • stdout=subprocess.PIPE: Captures the process's standard output so we can read it.
  • stderr=subprocess.STDOUT: Merges error output into stdout, so you'll see errors in real-time too (optional but helpful for debugging).
  • text=True: Automatically decodes bytes to strings, so you don't need to call .decode('utf-8') manually.
  • The loop uses readline() to get output as each line is written, and poll() checks if the process has terminated when we hit an empty line (to avoid infinite looping).

If you want to periodically check for output (instead of blocking on readline()), you can use poll() with a small sleep interval:

import subprocess
import time

cmd = 'netstat -nlpt'
process = subprocess.Popen(
    cmd,
    shell=True,
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    text=True
)

# Check for output at 0.1-second intervals while the process runs
while process.poll() is None:
    # Read all available output without blocking
    output = process.stdout.read()
    if output:
        print(output.strip())
    time.sleep(0.1)

# Read any remaining output after the process finishes
final_output = process.stdout.read()
if final_output:
    print(final_output.strip())

return_code = process.wait()

This second approach is useful if you need to run other tasks while waiting for output, but the first method is more efficient for pure streaming.

A quick security note: Using shell=True is safe here since netstat is a trusted system command, but if your command ever includes user-provided input, you should avoid shell=True and pass the command as a list (e.g., ['netstat', '-nlpt']) to prevent shell injection attacks.

内容的提问来源于stack exchange,提问作者Darshan Mahalinge Gowda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 10:02:55