python-3.x - 是否可以使用 Python 的 ANSI 转义码获取光标位置?

标签 python-3.x windows ansi-escape

(注:适用于 Windows 10 和 Python 3+)

我已经读过几篇关于如何使用 ANSI 转义码获取光标位置的帖子,但它们没有提供解决方案,至少对于 Python 来说是这样。维基百科 ( https://en.wikipedia.org/wiki/ANSI_escape_code ) 在其游标管理列表中包含以下 ANSI seq::

ESC 6n:DSR(设备状态报告)将光标位置 (CPR) 报告给应用程序(就像在键盘上键入一样)ESC[n;mR,其中 n 是行,m 是列.)

因此,如果您使用 print("\033[6n") 应用此操作,会发生的情况是响应被“推送”到键盘,并且只有在脚本终止后,您才会得到在 MS DOS 提示符下执行以下操作:^[[7;11R(数字取决于大小写)。

现在我真的不明白这有什么用!所以,我的问题是“我们‘最终’可以使用提到的条件(Windows、ANSI 代码和 Python)获取有关光标位置的信息吗?” ...我可以一次性结束这一章!

最佳答案

我找到了解决方案。您必须使用 msvcrt ,它是Python标准库的一部分。
我已经在 Windows 10 版本 2004 上使用 Python 3.8.7 尝试过此操作。
此方法不会将光标位置输出到键盘输入缓冲区。相反,它允许您将其保存到变量中以供进一步操作。

import msvcrt

# Added "\033[A" to move cursor up one line since 'print("\033[6n")' outputs a blank line
print("\033[A\033[6n")
buff = ""

keep_going = True
while keep_going:

    # getch() reads the keypress one character at a time,
    # since ANSI ESC[6n sequence fills the keyboard input buffer
    # 'decode("utf-8")' also works.
    buff += msvcrt.getch().decode("ASCII")

    # kbhit() returns True if a keypress is waiting to be read.
    # Once all the characters in the keyboard input buffer are read, the while loop exits
    keep_going = msvcrt.kbhit()

# Printing 'buff' variable outputs a blank line and no cursor position.
# By removing "\x1b" from the string in 'buff' variable,
# it will allow you to save the remaining string,
# containing the cursor position, to a variable for later use
newbuff = buff.replace("\x1b[", "")
print(newbuff)

结果:

1;1R

关于python-3.x - 是否可以使用 Python 的 ANSI 转义码获取光标位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64031571/

相关文章:

python - MyPy 参数默认值不兼容 - "Type[str]"与 "Callable[[str], obj]"

python - 从同一模型中的其他类获取模型属性

c++ - WMI 返回不同格式的信息

python - python 打印非字母 ASCII 字符的奇怪行为

Linux Bash shell : Leaving some ANSI codes (moSTLy color) and not interpreting some others from string in a function call

python - 为什么 isnumeric 不起作用?

python - InvalidArgumentError(回溯见上): indices[1] = 10 is not in [0, 10)

windows - 在 Windows 上使用 Mono 编译 F# 源代码

c - FindFirstChangeNotification 是用于 Windows 文件系统更改通知的最佳 API 吗?

c++ - 如何通过编程删除stdout中的字符?