(注:适用于 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/