![](/img/trans.png)
[英]readline set_completion_display_matches_hook requires return key before displaying prompt
[英]Why don't I see errors from 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()
当我运行它并点击Tab Tab时,我希望看到NameError: name 'someNonexistentMethod' is not defined
。 但是,实际上似乎根本没有发生任何事情(错误确实发生了,因此打印完成的其他函数不会运行;我只是没有看到错误)。 当我运行crash
,我确实看到了预期的错误,所以我知道错误处理在整个程序中工作正常,但只是在set_completion_display_matches_hook
回调中被破坏了。 这是为什么,我能做些什么吗?
当按下Tab Tab时,看起来readline
C-Binding 只是在调用钩子时忽略异常。
我相信问题的根源可能是 C 绑定readline.c中的这些行(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
预期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
。
我猜这是设计使然。 根据rlcompleter 文档:
在表达式求值过程中引发的任何异常都会被捕获、静音并返回 None 。
请参阅rlcompleter 源代码了解基本原理:
- 由完成函数引发的异常将被忽略(通常会导致完成失败)。 这是一个特性——因为 readline 将 tty 设备设置为原始(或 cbreak)模式,如果没有一些复杂的 hoopla 来保存、重置和恢复 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()
此脚本运行成功, example.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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.