pythonsyspdb

Inside pdb just before executing a Python script, can you set up your own sys.audit() hook?


Just before running a Python script inside pdb (using python -m pdb), I tried to add a handler for sys.audit() calls:

interact     ← puts pdb into interactive Python mode
import sys
def myaudit(event, args):
    print(f'audit: {event} with args={args}')
sys.addaudithook(myaudit)
ctrl-D       ← exits pdb’s interactive Python mode

Unfortunately, this yields:

... sys.addaudithook(myaudit)
  File "<console>", line 3
    sys.addaudithook(myaudit)
    ^^^
SyntaxError: invalid syntax

What am I missing?


Solution

  • You need to enter a blank line after the end of the function definition, so the interpreter knows you're done with the function:

    interact
    import sys
    def myaudit(event, args):
        print(f'audit: {event} with args={args}')
    
    sys.addaudithook(myaudit)
    ctrl-D