为什么我看不到来自readline.set_completion_display_matches_hook的错误?



请考虑以下代码:

#!/usr/bin/env python3
from cmd import Cmd
import readline
class mycmd(Cmd):
def match_display_hook(self, substitution, matches, longest_match_length):
someNonexistentMethod()
print()
for match in matches:
print(match)
print(self.prompt, readline.get_line_buffer(), sep='', end='', flush=True)
def do_crash(self, s):
someNonexistentMethod()
def do_quit(self, s):
return True
if __name__ == '__main__':
obj = mycmd()
readline.set_completion_display_matches_hook(obj.match_display_hook)
obj.cmdloop()

我希望在运行它并点击选项卡选项卡时看到NameError: name 'someNonexistentMethod' is not defined。但是,实际上似乎根本没有发生任何事情(错误确实发生了,因此将打印完成的其他函数不会运行;我只是没有看到错误(。当我运行crash时,我确实看到了预期的错误,所以我知道错误处理在整个程序中工作正常,但只是在set_completion_display_matches_hook回调中被破坏了。为什么会这样,我能做些什么吗?

为什么?

我猜这是设计使然。根据 rlcompleter 文档:

在表达式计算期间引发的任何异常都将被捕获、静默并返回 None。

有关基本原理,请参阅 rlcompleter 源代码:

  • 由完成器函数引发的异常将被忽略(通常会导致完成失败(。 这是一个功能 - 由于readline将tty设备设置为原始(或cbreak(模式,如果没有一些复杂的喧嚣来保存,重置和恢复tty状态,打印回溯将无法正常工作。

解决方法

作为解决方法,为了进行调试,请将钩子包装在捕获所有异常的函数中(或编写函数装饰器(,并使用日志记录模块将堆栈跟踪记录到文件中:

import logging
logging.basicConfig(filename="example.log", format='%(asctime)s %(message)s')
def broken_function():
raise NameError("Hi, my name is Name Error")
def logging_wrapper(*args, **kwargs):
result = None
try:
result = broken_function(*args, **kwargs)
except Exception as ex:
logging.exception(ex)
return result
logging_wrapper()

此脚本成功运行,示例.log包含日志消息和堆栈跟踪:

2020-11-17 13:55:51,714 Hi, my name is Name Error
Traceback (most recent call last):
File "/Users/traal/python/./stacktrace.py", line 12, in logging_wrapper
result = function_to_run()
File "/Users/traal/python/./stacktrace.py", line 7, in broken_function
raise NameError("Hi, my name is Name Error")
NameError: Hi, my name is Name Error

TL;博士

看起来readlineC 绑定只是在调用钩子时忽略异常,当按下 TabTab时。


我相信问题的根源可能是 C 绑定 readline 中的这些行 (1033-1049(。

r = PyObject_CallFunction(readlinestate_global->completion_display_matches_hook,
"NNi", sub, m, max_length);
m=NULL;
if (r == NULL ||
(r != Py_None && PyLong_AsLong(r) == -1 && PyErr_Occurred())) {
goto error;
}
Py_CLEAR(r);
if (0) {
error:
PyErr_Clear();
Py_XDECREF(m);
Py_XDECREF(r);
}

其中,如果发生错误,它只是被清除。参考PyErr_Clear((

我用于调试的步骤:

检查是否引发异常

我将函数更改为:

def match_display_hook(self, substitution, matches, longest_match_length):
try:
someNonexistentMethod()
except Exception as e:
print(e)

然后按预期打印name 'someNonexistentMethod' is not defined(以及所有其他预期的输出(。在此处引发任何其他异常不会退出命令提示符。

检查打印到stderr是否有效

最后,我检查是否可以通过添加以下内容打印到sys.stderr

def match_display_hook(self, substitution, matches, longest_match_length):
print("foobar", file=sys.stderr, flush=True)

按预期打印foobar

最新更新