Blessed

Pythonのターミナル処理ライブラリ。cursesの薄いラッパーとして動作し、クロスプラットフォーム対応とシンプルなAPIを提供します。

TUITerminalCursesCross-platformSimple

GitHub概要

jquast/blessed

Blessed is an easy, practical library for making python terminal apps

スター1,295
ウォッチ25
フォーク76
作成日:2014年3月1日
言語:Python
ライセンス:MIT License

トピックス

clicursesterminal

スター履歴

jquast/blessed Star History
データ取得日時: 2025/7/25 06:23

Blessed

Blessedは、Pythonのターミナル処理を簡素化するライブラリです。cursesライブラリの薄いラッパーとして動作し、クロスプラットフォーム対応とシンプルなAPIを提供します。cursesの複雑さを隠蔽し、より直感的なターミナルアプリケーション開発を可能にします。

主な特徴

シンプルなAPI

  • 直感的なインターフェース: cursesの複雑さを隠蔽
  • チェーンメソッド: メソッドチェーンによる簡潔な記述
  • コンテキストマネージャー: リソース管理の自動化

クロスプラットフォーム

  • Windows対応: Windows Console APIの活用
  • Unix系対応: ncurses/cursesライブラリの利用
  • 一貫したAPI: プラットフォーム差異の抽象化

豊富な機能

  • 色とスタイル: 256色、RGB色のサポート
  • 位置制御: カーソル位置の精密な制御
  • キー入力: 特殊キーの検出と処理

インストール

pip install blessed

基本的な使用方法

ターミナル初期化

from blessed import Terminal

term = Terminal()

print(term.home + term.clear)  # 画面をクリア
print(term.move_y(10) + "Hello, World!")  # 10行目に移動して出力

色とスタイル

from blessed import Terminal

term = Terminal()

# 基本的な色
print(term.red("Red text"))
print(term.green("Green text"))
print(term.blue("Blue text"))

# 背景色
print(term.on_yellow("Text on yellow background"))

# スタイル
print(term.bold("Bold text"))
print(term.italic("Italic text"))
print(term.underline("Underlined text"))

# 組み合わせ
print(term.bold_red_on_yellow("Bold red text on yellow background"))

キー入力処理

from blessed import Terminal

term = Terminal()

print("Press any key (ESC to quit):")

with term.cbreak(), term.hidden_cursor():
    while True:
        key = term.inkey()
        
        if key.is_sequence:
            print(f"Special key: {key.name}")
        else:
            print(f"Character: {key}")
        
        if key.name == 'KEY_ESCAPE':
            break

画面制御

from blessed import Terminal

term = Terminal()

with term.fullscreen(), term.cbreak():
    # フルスクリーンモード
    print(term.move(5, 10) + "Positioned text")
    print(term.move(10, 20) + term.red("Red text at specific position"))
    
    # 枠線の描画
    for x in range(term.width):
        print(term.move(0, x) + "*", end="")
        print(term.move(term.height - 1, x) + "*", end="")
    
    for y in range(term.height):
        print(term.move(y, 0) + "*", end="")
        print(term.move(y, term.width - 1) + "*", end="")
    
    term.inkey()  # キー入力待ち

実践的な例

メニューシステム

from blessed import Terminal

def show_menu(term, options, selected=0):
    term.clear()
    print(term.move(2, 5) + term.bold("Select an option:"))
    
    for i, option in enumerate(options):
        y = 4 + i
        if i == selected:
            print(term.move(y, 5) + term.reverse(f"> {option}"))
        else:
            print(term.move(y, 5) + f"  {option}")

def main():
    term = Terminal()
    options = ["Option 1", "Option 2", "Option 3", "Exit"]
    selected = 0
    
    with term.fullscreen(), term.cbreak():
        while True:
            show_menu(term, options, selected)
            
            key = term.inkey()
            
            if key.name == 'KEY_UP' and selected > 0:
                selected -= 1
            elif key.name == 'KEY_DOWN' and selected < len(options) - 1:
                selected += 1
            elif key.name == 'KEY_ENTER':
                if selected == len(options) - 1:  # Exit
                    break
                else:
                    print(term.move(10, 5) + f"You selected: {options[selected]}")
                    term.inkey()
            elif key.name == 'KEY_ESCAPE':
                break

if __name__ == "__main__":
    main()

プログレスバー

from blessed import Terminal
import time

def show_progress(term, progress, total):
    width = 50
    filled = int(width * progress / total)
    bar = "=" * filled + "-" * (width - filled)
    percentage = int(100 * progress / total)
    
    print(term.move(10, 10) + f"Progress: [{bar}] {percentage}%")

def main():
    term = Terminal()
    
    with term.fullscreen():
        print(term.move(8, 10) + term.bold("Processing..."))
        
        for i in range(101):
            show_progress(term, i, 100)
            time.sleep(0.1)
        
        print(term.move(12, 10) + term.green("Complete!"))
        term.inkey()

if __name__ == "__main__":
    main()

テキストエディタの基本機能

from blessed import Terminal

class SimpleEditor:
    def __init__(self):
        self.term = Terminal()
        self.lines = [""]
        self.cursor_x = 0
        self.cursor_y = 0
    
    def draw(self):
        print(self.term.home + self.term.clear)
        
        # ステータスライン
        status = f"Line: {self.cursor_y + 1}, Col: {self.cursor_x + 1}"
        print(self.term.move(0, 0) + self.term.reverse(status.ljust(self.term.width)))
        
        # テキスト表示
        for i, line in enumerate(self.lines):
            print(self.term.move(i + 2, 0) + line)
        
        # カーソル位置
        print(self.term.move(self.cursor_y + 2, self.cursor_x), end="")
    
    def run(self):
        with self.term.fullscreen(), self.term.cbreak():
            while True:
                self.draw()
                key = self.term.inkey()
                
                if key == chr(27):  # ESC
                    break
                elif key.name == 'KEY_UP' and self.cursor_y > 0:
                    self.cursor_y -= 1
                    self.cursor_x = min(self.cursor_x, len(self.lines[self.cursor_y]))
                elif key.name == 'KEY_DOWN' and self.cursor_y < len(self.lines) - 1:
                    self.cursor_y += 1
                    self.cursor_x = min(self.cursor_x, len(self.lines[self.cursor_y]))
                elif key.name == 'KEY_LEFT' and self.cursor_x > 0:
                    self.cursor_x -= 1
                elif key.name == 'KEY_RIGHT' and self.cursor_x < len(self.lines[self.cursor_y]):
                    self.cursor_x += 1
                elif key and not key.is_sequence:
                    # 文字入力
                    line = self.lines[self.cursor_y]
                    self.lines[self.cursor_y] = line[:self.cursor_x] + key + line[self.cursor_x:]
                    self.cursor_x += 1

if __name__ == "__main__":
    editor = SimpleEditor()
    editor.run()

他のライブラリとの比較

特徴BlessedcursesRichUrwid
クロスプラットフォーム×
シンプルさ
学習コスト
機能の豊富さ
パフォーマンス

使用事例

  • コマンドラインツール: 対話的なCLIアプリケーション
  • システム監視: リアルタイムステータス表示
  • ゲーム: シンプルなターミナルゲーム
  • 教育用ツール: プログラミング学習支援ツール

コミュニティとサポート

  • GitHub: アクティブなメンテナンス
  • ドキュメント: 詳細なAPIリファレンス
  • 互換性: Python 2.7-3.11対応
  • 安定性: 長期間にわたる実績

Blessedは、cursesの複雑さを隠蔽しながら強力なターミナル制御機能を提供する、実用的で信頼性の高いライブラリです。