在 input() 上获取事件

Arn*_*eev 3 python

我想获取一个事件或至少在每次input()调用函数时运行该函数。这应该input在不以任何方式包装函数的情况下发生。

有没有办法在input()不直接修改函数的情况下获取事件或某些信号?

Mis*_*agi 5

从 Python 3.8 开始,人们可以使用审核事件来获取调用input通知。这允许指定一个钩子,该钩子在所有事件上被调用,并且可以过滤掉input及其提示。

import sys

def intercept_input(event, *args):
    # the hook is called on all events
    # only react if it is an interesting one
    if event == "builtins.input":
        # the only input argument is the prompt message
        prompt, = args
        print("Querying for input as", repr(prompt))


sys.addaudithook(intercept_input)
input("Hello?")
Run Code Online (Sandbox Code Playgroud)

请参阅有关审核挂钩如何工作的sys.addaudithook函数,以及审核挂钩接收的事件的审核事件表。


请注意,如果目的是捕获输入,则包装input和替换它builtins.input会更简单、更快。