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

如何获取终端光标位置?优先转义码方案,可接受Windows控制台API

获取终端光标位置的实现方法

一、使用ANSI转义码(跨平台优先方案)

绝大多数现代终端(Linux/macOS终端、Windows Terminal、开启VT100支持的CMD)都兼容ANSI转义序列,可按以下步骤获取光标位置:

  1. 向终端发送查询光标位置的转义码:\x1b[6n(或八进制格式\033[6n)
  2. 终端会返回格式为\x1b[<行号>;<列号>R的响应(行、列号从1开始计数)
  3. 读取并解析该响应,提取出行号和列号

示例代码(Python)

import sys
import termios
import tty

def get_cursor_position():
    old_settings = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        sys.stdout.write('\x1b[6n')
        sys.stdout.flush()
        
        response = ''
        while True:
            char = sys.stdin.read(1)
            response += char
            if char == 'R':
                break
        
        _, coords = response.split('[')
        row, col = coords.split(';')
        return (int(row), int(col[:-1]))
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)

row, col = get_cursor_position()
is_start_of_line = (col == 1)
print(f"光标位置:行{row},列{col}")
print(f"是否处于新行起始位置:{is_start_of_line}")

二、Windows控制台API方案(仅Windows环境)

针对未开启VT100支持的传统CMD,可直接调用Windows原生API获取光标位置,核心使用GetConsoleScreenBufferInfo函数:

示例代码(C语言)

#include <windows.h>
#include <stdio.h>

int main() {
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO csbi;

    if (!GetConsoleScreenBufferInfo(hConsole, &csbi)) {
        printf("获取控制台信息失败,错误码:%lu\n", GetLastError());
        return 1;
    }

    DWORD row = csbi.dwCursorPosition.Y + 1;
    DWORD col = csbi.dwCursorPosition.X + 1;
    BOOL is_start_of_line = (csbi.dwCursorPosition.X == 0);

    printf("光标位置:行%lu,列%lu\n", row, col);
    printf("是否处于新行起始位置:%s\n", is_start_of_line ? "是" : "否");

    return 0;
}

补充说明

  • Windows下使用ANSI转义码前,需通过SetConsoleMode开启ENABLE_VIRTUAL_TERMINAL_PROCESSING模式
  • Windows Terminal、PowerShell默认支持ANSI转义序列,无需额外配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:52:13