【问题标题】:Is it possible to get cursor position using ANSI escape codes with Python?是否可以在 Python 中使用 ANSI 转义码获取光标位置?
【发布时间】:2021-01-09 20:50:20
【问题描述】:

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

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

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

所以,如果你应用这个,使用print("\033[6n"),会发生什么是响应被“推送”到键盘,只有在脚本终止后,你会在 MS DOS 提示符下看到以下内容:^[[ 7;11R(数字视情况而定)。

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

【问题讨论】:

  • 不,使用 ANSI 转义码是不可能的。在安装 wheelcurses 包后,您必须使用 curses.getsyx 方法。
  • 我很清楚。这就是为什么我强调“使用上述条件”。我还能强调多少?

标签: python-3.x windows ansi


【解决方案1】:

我已经在我的手机上尝试过,它似乎有效, 我打开一个文件,而不是在屏幕上打印“\033[6n”,而是将它打印到一个文件中

with open("fn.txt", "w+") as file:
    print("\033[6n", file=file) 

然后我可以读取文件的内容并将其打印到屏幕上

with open("fn.txt","r+") as file:
    print(file.read())

希望对你有帮助,再见!

顺便说一句,我在 Android 8.1.0 上使用 pydroid3

编辑:我已将两个 whiles 压缩为一个,并将其包围在一个函数中

def dsr():
    with open("fn.txt", "w+") as file:
        print("\033[6n", file=file)
        file.seek(0)
        return file.read()

【讨论】:

  • 好的,我在电脑上试过了,没用
  • 谢谢。这是在极少数情况下使用的解决方法。你会时不时地这样做来检查光标位置吗?这是非常低效的编程方式。顺便说一句,为什么使用print() 写入文件句柄而不是标准的file.write("\033[6n") 方法??
  • 我在 Windows 10 桌面上使用 Python 3.8.7 进行了尝试。不幸的是,这个解决方案不起作用。
  • 你可以print("←[6n") !!! (当然,无论哪种方式,它都行不通。)
  • 不管怎样,这和获取光标位置有什么关系???
【解决方案2】:

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

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

【讨论】:

  • 这和获取光标位置有什么关系???
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-20
相关资源
最近更新 更多