在控制台的指定行和列位置显示文字

在Python中,你可以使用以下几种方法在控制台的指定行和列位置显示文字:

1. 使用 print\033 ANSI转义码(跨平台,但Windows 10+需要启用VT支持)

# 移动光标到第5行第10列并显示文字
print("\033[4;10HHello at row 5, column 10")  # 注意:行号从1开始

2. 使用 curses 模块(Linux/macOS原生支持,Windows需要额外库)

import curses

def main(stdscr):
    stdscr.clear()
    stdscr.addstr(4, 9, "Hello at row 5, column 10")  # 行/列从0开始
    stdscr.refresh()
    stdscr.getch()

curses.wrapper(main)

3. 使用 win32console(仅Windows)

import win32console

hOut = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE)
hOut.SetConsoleCursorPosition(4, 9)  # 行/列从0开始
print("Hello at row 5, column 10")

4. 使用第三方库 blessed(跨平台推荐)

from blessed import Terminal

term = Terminal()
with term.location(x=9, y=4):  # 列/行从0开始
    print("Hello at row 5, column 10")

5. 简单方法:使用空格手动定位(仅限固定宽度)

# 打印空行定位到第5行
print("\n" * 4)  
# 打印空格定位到第10列
print("         " + "Hello")  # 9个空格 + 内容

最佳实践建议:

  • 跨平台需求:使用 blessed 库(需要安装:pip install blessed
  • Windows专用win32console(需安装pywin32
  • Unix-like系统:直接使用 curses
  • 简单场景:ANSI转义码(但注意Windows可能需要启用VT支持)

完整ANSI转义码示例:

# 启用VT100支持(Windows 10+)
import os
os.system('')  # 仅Windows需要

# 移动光标到第5行第10列(行/列从1开始)
print("\033[5;10HHello World!")

# 重置光标位置
print("\033[0;0H")

注意:现代终端(如VS Code集成终端、Windows Terminal等)通常都支持ANSI转义码,但旧版Windows cmd可能需要先运行os.system('')来启用VT支持。

posted @ 2025-06-24 11:26  nxhujiee  阅读(5)  评论(0)    收藏  举报