Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an event on input()

Tags:

python

I want to get an event or at least run a function each time the input() function is called. This should happen without wrapping the input function in any way.

Is there a way to get an event or some signal that the input() function is called without modifying it directly?

like image 543
Arneev Avatar asked Jul 09 '26 09:07

Arneev


1 Answers

Since Python 3.8, one can use an audit event to get notified on input calls. This allows to specify a hook which gets called on all events and may filter out the input and its prompt.

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?")

See the sys.addaudithook function on how audit hooks work, and the audit event table for the events an audit hook receives.


Note that if the intention is to capture the input, then wrapping input and replacing it in builtins.input is both simpler and faster.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!