2011-03-02 60 views
5

我有一個使用print()函數將輸出發送到DOS命令窗口(我使用Windows 7)的Python腳本,但是我想阻止(或隱藏)在下一個可用輸出位置閃爍的光標。有沒有人有任何想法我可以做到這一點?我查看了DOS命令列表,但找不到合適的東西。如何在命令窗口中關閉閃爍的光標?

任何幫助,將不勝感激。 Alan

+0

據我可以確定,你不能使用標準的DOS命令窗口來做到這一點。您需要提供自己的輸出窗口,例如使用TKInter或wxPython。 – kindall 2011-03-03 00:51:12

回答

3

據我們所知,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) 
+0

感謝您的回覆。你是對的 - 我使用的是Python 3.1,所以它看起來像我被遊標卡住了一段時間:-(關心。 – 2011-03-07 13:26:03

9

我已經寫了一個跨平臺的顏色庫結合使用與COLORAMA(http://pypi.python.org/pypi/colorama)爲Python 3.完全隱藏在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下測試的。