如何在python中更改指针的位置? [英] How to change the location of the pointer in python?

查看:392
本文介绍了如何在python中更改指针的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在程序获取某些特殊单词时绘制它们,实际上是实时的. 所以我写了一段很好的代码,但是我仍然不能用键盘上的移动键改变指针的位置,并从我移动的位置开始输入文字. 谁能给我一个提示,怎么做? 这是代码:

I want to paint some special words while the program is getting them , actually in real-time . so I've wrote this piece of code which do it quite good but i still have problem with changing the location of the pointer with move keys on keyboard and start typing from where i moved it . can anyone give me a hint how to do it ? here is the CODE :

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()

推荐答案

简单易行

您似乎已经在使用colorama模块,定位光标的最简单,最便捷的方法应该是使用相应的ANSI控件序列(请参阅:

Doing it the easy way

As you already seem to be using the colorama module, the most easy and portable way to position the cursor should be to use the corresponding ANSI controlsequence (see: http://en.m.wikipedia.org/wiki/ANSI_escape_code)

您要查找的应该是CUP –光标位置(CSI n; m H),将光标放置在第n行和第m列中.

The one you are looking for should be CUP – Cursor Position (CSI n ; m H)positioning the cursor in row n and column m.

然后,代码将如下所示:

The code would look like this then:

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

用手做的事情很痛苦

即使在Windows控制台中也无法使事情正常运行的漫长而痛苦的方式,而对于上述控制顺序一无所知,那就是使用Windows API.

Suffering by doing everything by hand

The long and painful way to make things work even in a windows console, that doesn't know about the above mentioned control sequence would be to use the windows API.

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

Fortunately the colorama module will do this (hard) work for you, as long as you don't forget a call to colorama.init().

出于教学目的,我留下了最痛苦的方法的代码,省去了colorama模块的功能,而是手工完成了所有事情.

For didactic purposes, I left the code of the most painful approach leaving out the functionality of the colorama module, doing everything by hand.

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版本.

As already stated in the comment section this attempt still leaves you with the problem, that your application will only work in the named console, so maybe you will still want to supply a curses version too.

要检测是否支持curses或必须使用Windows API,可以尝试执行以下操作.

To detect if curses is supported or you will have to use the windows API, you might try something like this.

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

这篇关于如何在python中更改指针的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆