Python 中的 N-curses:如何捕获并打印非 ASCII 字符?

2024-02-13

我想用 ncurses/python 制作一个小程序,并且能够使用/输入法语和日语。我知道我应该设置区域设置并使用 unicode 标准。

但是如何处理 screen.getch() 的结果呢?我想在 ncurses 窗口中显示键入的字符,而不管语言如何。

我知道一些 unicode 转换是必要的,但找不到该怎么做(而且我已经搜索了很多:这种字符转换业务对于业余爱好者来说并不容易理解)。

附加问题:似乎对于非 ascii 字符,我们必须使用 addstr() 而不是 addch()。同样,我应该使用 getstr() 而不是 getch() 吗?

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import curses
from curses import wrapper
import locale

locale.setlocale(locale.LC_ALL, '')

def main(scr):
    # Following lines are some sort of "proof of concept"
    # Indeed it print latin or japanese characters allright
    scr.addstr(0, 0, u'\u3042'.encode('utf-8')) # print あ
    scr.addstr(1, 0, 'é'.encode('utf-8'))       # print é

    # But here I would like to type in a character and have it displayed onscreen
    while (True):
        car = scr.getch()
        if car == 27: # = Escape key
            break
        else:
        # What should I put between those parenthesis to
        # print the typed character on the third line of the screen 
            scr.addstr(3, 0, ???? )

wrapper(main)

unctrl https://docs.python.org/2/library/curses.html#curses.unctrl是要使用的函数,其结果来自getch https://docs.python.org/3/library/curses.html#curses.window.getch:

curses.unctrl(ch)

返回一个字符串,它是可打印的表示字符 ch.控制字符显示为插入符号后跟字符,例如^C。打印字符保持原样。

如果你想直接读取UTF-8,使用get_wch https://docs.python.org/3/library/curses.html#curses.window.get_wch(这在 python2 包装器中不可用):

window.get_wch([y, x])

获得宽广的性格。对于大多数键返回一个字符,对于功能键、小键盘键和其他特殊键返回整数。在无延迟模式下,如果没有输入,则引发异常。

新版本中3.3.

即使that,您仍然必须确保区域设置已初始化。 Python 文档假定您有权访问 ncurses 文档:

  • 初始化 https://invisible-island.net/ncurses/man/ncurses.3x.html#h3-Initialization,在 ncurses 手册页中
  • 获取_wch、wget_wch、mvget_wch、mvwget_wch、unget_wch https://invisible-island.net/ncurses/man/curs_get_wch.3x.html- 获取(或推送 背面)来自curses终端键盘的宽字符
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 中的 N-curses:如何捕获并打印非 ASCII 字符? 的相关文章

随机推荐