我正在按照文档 https://docs.python.org/3/howto/curses.html 在 Python 中设置
curses
应用程序。根据文档,建议使用 wrapper
,因为它会自动初始化所有内容并处理异常。
提供的示例非常基本,仅使用单个函数。我想使用一个类来包装curses 功能并触发对TUI 的更改。在这种情况下我将如何使用包装器?下面是我迄今为止尝试过的示例,但运行代码会以奇怪的对齐方式输出回溯,并使终端处于损坏状态,然后需要
reset
。
import curses
from curses import wrapper
class Test:
def __init__(self, stdscr):
self._stdscr = stdscr
@classmethod
def create(cls):
_cls = wrapper(cls)
return _cls
def start(self):
self._screen = curses.newpad(100, 100)
self._screen.addstr(2, 2, 'test title', curses.A_STANDOUT)
screen_rows, screen_cols = self._stdscr.getmaxyx()
self._screen.refresh(0, 0, 0, 0, screen_rows - 1, screen_cols - 1)
while True:
self._stdscr.getch()
1/0 # example of uncaught exception
t = Test.create()
t.start()
输出
Traceback (most recent call last):
File "/tmp/test/test.py", line 27, in <module>
t.start()
File "/tmp/test/test.py", line 23, in start
1/0
~^~
ZeroDivisionError: division by zero
本质上我正在寻找一种解决方案来处理任何未捕获的异常
您应该添加一个 try 和 except 块来处理零除错误 如果您在正确的位置添加以下内容,您的代码应该运行得更好
while True:
try:
key = self._stdscr.getch()
except ZeroDivisionError:
pass