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

如何用Python统计输出行数并实现终端首行持续更新时间

解决方案

一、统计Python脚本输出的行数

要统计脚本自身的输出行数,可通过重定向标准输出、捕获输出内容后统计:

import sys
from io import StringIO

def count_output_lines():
    # 保存原始标准输出
    original_stdout = sys.stdout
    # 创建内存缓冲区用于捕获输出
    captured_output = StringIO()
    sys.stdout = captured_output

    # 此处替换为你实际的输出代码
    print("测试行1")
    print("测试行2")
    print("测试行3")

    # 恢复原始标准输出
    sys.stdout = original_stdout
    # 按行分割捕获的内容并统计行数
    output_lines = captured_output.getvalue().splitlines()
    return len(output_lines)

# 调用示例
print(f"输出总行数: {count_output_lines()}")

二、让时间始终显示在终端第一行

无需获取输出行数,直接用ANSI转义序列定位光标到第一行开头,就能实现固定位置显示时间,修改后的代码如下:

from datetime import datetime
import time

# ANSI转义序列:将光标移动到第1行第1列
CURSOR_TO_FIRST_LINE = '\033[1;1H'
# ANSI转义序列:清除当前行内容
LINE_CLEAR = '\x1b[2K'

def displayTime():
    while True:
        # 格式化当前时间
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        # 定位光标、清除行、打印时间,强制刷新输出
        print(f"{CURSOR_TO_FIRST_LINE}{LINE_CLEAR}{current_time}", end='', flush=True)
        time.sleep(1)

# 模拟已有输出内容
print("输出行1")
print("输出行2")
print("输出行3")

# 启动时间显示
displayTime()

核心说明

  • \033[1;1H:直接将光标定位到终端第一行开头,不受之前输出行数影响,适配PowerShell环境。
  • flush=True:强制刷新输出缓冲区,避免时间显示延迟。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 09:07:19