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

Moh*_*shi 5 python windows pointers

我想在程序获取它们时绘制一些特殊的单词,实际上是实时的.所以我写了这段代码,它做得非常好,但我仍然有问题,用键盘上的移动键更改指针的位置,并从我移动它的位置开始键入.任何人都可以给我一个提示怎么做?这是代码:

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()
Run Code Online (Sandbox Code Playgroud)

mik*_*yra 7

这样做很简单

由于您似乎已经在使用该colorama模块,因此定位光标的最简单,最便携的方法应该是使用相应的ANSI控制序列(请参阅:http://en.m.wikipedia.org/wiki/ANSI_escape_code)

您正在寻找的应该是CUP - 光标位置(CSI n; m H)将光标定位在行n和列m中.

代码看起来像这样:

def move (y, x):
    print("\033[%d;%dH" % (y, x))
Run Code Online (Sandbox Code Playgroud)

苦于手工做所有事情

即使在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)
Run Code Online (Sandbox Code Playgroud)

正如评论部分已经说明的那样,这个尝试仍然会让你遇到问题,你的应用程序只能在命名控制台中运行,所以也许你仍然想要提供一个curses版本.

要检测是否支持curses,或者您必须使用Windows API,您可以尝试这样的方法.

#==== IMPORTS =================================================================
try:
    import curses
    HAVE_CURSES = True
except:
    HAVE_CURSES = False
    pass
Run Code Online (Sandbox Code Playgroud)