如何关闭命令窗口中的闪烁光标?
我有一个Python脚本,它通过print()函数把输出发送到DOS命令窗口(我在用Windows 7),但是我想让光标不在下一个输出位置闪烁。有没有人知道我该怎么做?我查过一些DOS命令,但找不到合适的。
任何帮助都很感激。
阿兰
4 个回答
20
如果你在2019年看到这个,有一个叫“cursor”的Python3模块,它其实就是提供了隐藏和显示的方法。你只需要安装这个模块,然后用下面的代码:
import cursor
cursor.hide()
就完成了!
33
我一直在写一个跨平台的颜色库,目的是和colorama一起在python3中使用。为了在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上测试过的。
3
从目前的情况来看,似乎没有适用于Windows的curses模块,而这个模块很可能是你需要的。最接近你需求的,是由Fredrik Lundh在effbot.org上写的Console模块。不过,这个模块只适用于Python 3之前的版本,而你似乎正在使用的是Python 3。
在Python 2.6和Windows XP中,下面的代码可以打开一个控制台窗口,让光标变得不可见,打印出“Hello, world!”,然后在两秒后关闭这个控制台窗口:
import Console
import time
c = Console.getconsole()
c.cursor(0)
print 'Hello, world!'
time.sleep(2)