【问题标题】:how to change some words color real time while accepting input in python [closed]如何在接受python输入时实时更改一些单词的颜色[关闭]
【发布时间】:2014-12-12 10:34:20
【问题描述】:

我正在尝试编写一段代码,它将接受一个字符串作为输入,如果用户输入了一个特定的单词,它会将单词的颜色更改为红色,但我的意思是当用户输入时都是实时的字符串不是在他按下 Enter 之后。 我知道它应该通过线程来完成,但问题是我不知道如何使线程实时工作。 有人可以帮帮我吗?

【问题讨论】:

标签: python multithreading input colors


【解决方案1】:

这是从标准输入一次读取一个字符的方法,取自this answer

class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch


class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()

getch = _Getch()

此代码的一种可能用法如下所示。您读取字符并将它们存储在变量中。然后将其打印到stdout 并用colorama 着色。这段代码只是一个例子,它还有一件事不能正常工作:“空间”的处理。但是,如果您尝试一下,您会发现这些单词是实时着色的。需要进行额外的调整才能实时正确输出所有字母,包括空格。但我把这留给你,这足以让你开始。

import sys
from colorama import Fore

special_words = ['bannanas', 'eggs', 'ham']
my_text = ''
while True:
    c = getch()
    if ord(c) == 13:  # newline, stop
        break 
    my_text += c    

    sys.stdout.write("\r")  # move to the line beginning
    for word in my_text.split():
        if word in special_words:
            sys.stdout.write(Fore.RED + word + " ")
        else:
            sys.stdout.write(Fore.RESET + word + " ")
    sys.stdout.flush()

# reset the color when done
print(Fore.RESET)

【讨论】:

  • 谢谢你的解释。但我想在 IDLE shell 中进行。不在 GUI 中。可以在那里做吗?用简单的 raw_input 方法考虑它
  • 谁能帮助我如何在我的输入中使用此代码?我的意思是如何获取输入并突出显示单词,而不仅仅是使用 getch 读取字符?
  • 你读过我的回答吗?我为你写了 90% 的代码。我想我毕竟一直在喂..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-22
  • 2023-03-30
  • 1970-01-01
  • 2015-08-16
  • 2023-04-02
  • 2015-09-14
相关资源
最近更新 更多