如何在python中更改指针的位置?

2024-06-26 00:23:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想画一些特别的词,而程序正在得到它们,实际上是实时的。 所以我写了这段代码,它做得很好,但我仍然有问题,改变指针的位置与键盘上的移动键,并开始键入从我移动它。 有人能告诉我怎么做吗? 代码如下:

from colorama import init
from colorama import Fore
import sys
import msvcrt
special_words = ['test' , 'foo' , 'bar', 'Ham']
my_text = ''
init( autoreset = True)
while True:
    c = msvcrt.getch()
    if ord(c) == ord('\r'):  # newline, stop
        break
    elif ord(c) == ord('\b') :
        sys.stdout.write('\b')
        sys.stdout.write(' ')
        my_text = my_text[:-1]
        #CURSOR_UP_ONE = '\x1b[1A'
        #ERASE_LINE = '\x1b[2K'
        #print ERASE_LINE,
    elif ord(c) == 224 :
        set (-1, 1)
    else:
        my_text += c

    sys.stdout.write("\r")  # move to the line beginning
    for j, word in enumerate(my_text.split()):
        if word in special_words:
            sys.stdout.write(Fore.GREEN+ word)
        else:
            sys.stdout.write(Fore.RESET + word)
        if j != len(my_text.split())-1:
            sys.stdout.write(' ')
        else:
            for i in range(0, len(my_text) - my_text.rfind(word) - len(word)):
                sys.stdout.write(' ')
    sys.stdout.flush()

Tags: 代码textinfromimportlenifmy
1条回答
网友
1楼 · 发布于 2024-06-26 00:23:55

做起来很简单

由于您似乎已经在使用colorama模块,定位光标的最简单和可移植的方法应该是使用相应的ANSI controlsequence(请参见:http://en.m.wikipedia.org/wiki/ANSI_escape_code

您要查找的应该是CUP-Cursor Position(CSI n;m H),它将光标定位在行n和列m中

代码如下所示:

def move (y, x):
    print("\033[%d;%dH" % (y, x))

手忙脚乱

即使在windows控制台中,也不知道上面提到的控制序列,要想让事情正常工作,漫长而痛苦的方法就是使用windows API。

幸运的是,colorama模块将为您完成这项(艰苦的)工作,只要您不忘记对colorama.init()的调用。

出于说教的目的,我留下了最痛苦方法的代码,去掉了colorama模块的功能,手工完成所有事情。

import ctypes
from ctypes import c_long, c_wchar_p, c_ulong, c_void_p


#==== GLOBAL VARIABLES ======================

gHandle = ctypes.windll.kernel32.GetStdHandle(c_long(-11))


def move (y, x):
   """Move cursor to position indicated by x and y."""
   value = x + (y << 16)
   ctypes.windll.kernel32.SetConsoleCursorPosition(gHandle, c_ulong(value))


def addstr (string):
   """Write string"""
   ctypes.windll.kernel32.WriteConsoleW(gHandle, c_wchar_p(string), c_ulong(len(string)), c_void_p(), None)

正如在注释部分已经指出的,这个尝试仍然会给您留下问题,您的应用程序将只在命名控制台中工作,因此您可能仍然希望提供curses版本。

若要检测是否支持游标,或者必须使用windows API,可以尝试以下操作。

#==== IMPORTS =================================================================
try:
    import curses
    HAVE_CURSES = True
except:
    HAVE_CURSES = False
    pass

相关问题 更多 >