【发布时间】:2011-03-02 23:25:46
【问题描述】:
我有一个 Python 脚本,它使用 print() 函数将输出发送到 DOS 命令窗口(我使用的是 Windows 7),但我想防止(或隐藏)光标在下一个可用输出位置闪烁.有谁知道我该怎么做?我查看了 DOS 命令列表,但找不到合适的。
任何帮助将不胜感激。 艾伦
【问题讨论】:
标签: python text-cursor command-window
我有一个 Python 脚本,它使用 print() 函数将输出发送到 DOS 命令窗口(我使用的是 Windows 7),但我想防止(或隐藏)光标在下一个可用输出位置闪烁.有谁知道我该怎么做?我查看了 DOS 命令列表,但找不到合适的。
任何帮助将不胜感激。 艾伦
【问题讨论】:
标签: python text-cursor command-window
我一直在为 python3 编写一个跨平台颜色库以与colorama 结合使用。在 windows 或 linux 上完全隐藏光标:
import sys
import os
if os.name == 'nt':
import msvcrt
import ctypes
class _CursorInfo(ctypes.Structure):
_fields_ = [("size", ctypes.c_int),
("visible", ctypes.c_byte)]
def hide_cursor():
if os.name == 'nt':
ci = _CursorInfo()
handle = ctypes.windll.kernel32.GetStdHandle(-11)
ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci))
ci.visible = False
ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci))
elif os.name == 'posix':
sys.stdout.write("\033[?25l")
sys.stdout.flush()
def show_cursor():
if os.name == 'nt':
ci = _CursorInfo()
handle = ctypes.windll.kernel32.GetStdHandle(-11)
ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci))
ci.visible = True
ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci))
elif os.name == 'posix':
sys.stdout.write("\033[?25h")
sys.stdout.flush()
以上是选择性复制和粘贴。从这里你应该几乎可以做你想做的事。假设我没有弄乱复制和粘贴,这是在 Windows Vista 和 Linux / Konsole 下测试的。
【讨论】:
\033[?25h 和 \033[?25l 到底是做什么的?看起来很神奇。
printf "\033[?25h"(在 bash 中)。
对于在 2019 年看到这一点的任何人,有一个名为“cursor”的 Python3 模块,它基本上只有 hide 和 show 方法。安装光标,然后使用:
import cursor
cursor.hide()
你就完成了!
【讨论】:
我很惊讶之前没有人提到这一点,但实际上你不需要任何库来做到这一点。
只需使用print('\033[?25l', end="") 隐藏光标即可。
您可以使用print('\033[?25h', end="") 将其显示回来。
就这么简单:)
【讨论】:
据我们所知,curses 模块没有 Windows 端口,这很可能是您需要的。最能满足您需求的是由 Fredrik Lundh 在 effbot.org 撰写的 Console module。不幸的是,该模块仅适用于 Python 3 之前的版本,而这正是您所使用的。
在 Python 2.6/WinXP 中,以下代码打开一个控制台窗口,使光标不可见,打印“Hello, world!”然后在两秒后关闭控制台窗口:
import Console
import time
c = Console.getconsole()
c.cursor(0)
print 'Hello, world!'
time.sleep(2)
【讨论】: