首頁 >後端開發 >Python教學 >如何從使用者輸入讀取單一字元而不阻塞或回顯跨平台?

如何從使用者輸入讀取單一字元而不阻塞或回顯跨平台?

Linda Hamilton
Linda Hamilton原創
2024-12-29 19:30:12512瀏覽

How Can I Read a Single Character from User Input Without Blocking or Echoing Cross-Platform?

非阻塞輸入:跨平台讀取單一字元

從使用者輸入讀取單一字元而不將其回顯到螢幕上是各種程式場景中的常見需求。雖然 Windows 為此目的提供了特定功能,但實現跨平台解決方案可能具有挑戰性。

跨平台方法

為了克服此限制,利用 ActiveState Recipes 庫的多功能方法提供了一種可以跨 Windows、Linux和OSX:

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

用法

要使用此方法,請實例化_Getch 類別並呼叫其可呼叫介面以從使用者的輸入中讀取單一字元:

ch = getch()

這種方法提供了一種非阻塞輸入機制,允許開發者從使用者無需中斷程式流程或將其回顯到螢幕上。它是快速響應和互動式命令列應用程式的寶貴工具。

以上是如何從使用者輸入讀取單一字元而不阻塞或回顯跨平台?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn