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

Python调用bash脚本:实时输出同时捕获数字行的实现方法

解决方案:实时输出bash脚本并捕获纯数字行

你可以通过维护一个行缓冲区来实现——逐字符读取时实时输出,同时把字符暂存到缓冲区,遇到换行符时再判断该行是否为纯数字行。下面是修改后的Python脚本:

import subprocess
import sys

def run_dot_script():
    command = ['bash', './dots.sh']
    # 使用text=True自动解码字节流为字符串,简化代码
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

    line_buffer = ""
    numeric_lines = []  # 用来存储捕获到的纯数字行

    try:
        while True:
            char = process.stdout.read(1)
            if not char:
                break
            # 实时输出当前字符并立即刷新,保证点号/星号实时显示
            sys.stdout.write(char)
            sys.stdout.flush()

            if char == '\n':
                # 遇到换行符,处理当前缓存的行内容
                stripped_line = line_buffer.strip()
                if stripped_line.isdigit():
                    numeric_lines.append(stripped_line)
                line_buffer = ""
            else:
                # 非换行符,添加到行缓冲区
                line_buffer += char
        # 处理脚本结束后可能遗留的无换行内容
        if line_buffer:
            stripped_line = line_buffer.strip()
            if stripped_line.isdigit():
                numeric_lines.append(stripped_line)
    finally:
        # 等待进程完全结束,替代原有的terminate+wait,更稳妥
        process.wait()

    # 输出捕获到的结果
    print("\n--- 捕获到的纯数字行 ---")
    for line in numeric_lines:
        print(line)

run_dot_script()

关键说明:

  • 实时输出:保持逐字符读取并立即刷新标准输出,确保bash脚本里的点号、星号能实时显示,不会因为缓冲区堆积延迟输出。
  • 行缓存与判断:用line_buffer暂存每行的字符,遇到换行时检查内容是否为纯数字(str.isdigit()),如果是就存入列表。
  • 兼容无换行的末尾行:循环结束后检查缓冲区剩余内容,避免最后一行没有换行符导致内容遗漏。
  • 简化解码:使用text=True参数让subprocess自动处理字节到字符串的转换,省去手动解码的步骤。

如果需要支持负数、小数这类数字格式,可以把判断逻辑改成正则匹配:

import re
# ...
if re.fullmatch(r'^-?\d+(\.\d+)?$', stripped_line):
    numeric_lines.append(stripped_line)

内容的提问来源于stack exchange,提问作者Simd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 09:14:52