How can I debug manually typed expression and statements in pdb?

后端 未结 2 1634
小蘑菇
小蘑菇 2021-01-12 09:39

In pdb (or ipdb) we can execute statements and evaluate expressions with the ! or p commands:

p expression
     Evaluate the

2条回答
  •  孤独总比滥情好
    2021-01-12 10:11

    I think you're looking for the (d)ebug command which, for some reason, is not specified in the Debugger Commands. Just for future reference, pdb has a nice set of commands specified (which you can see by typing help in the interactive prompt). On to the debug command:

    (Pdb) help debug
    debug code
            Enter a recursive debugger that steps through the code
            argument (which is an arbitrary expression or statement to be
            executed in the current environment).
    

    Which seems to do what you're after. Using your sample script from the terminal:

    python -m pdb pdbscript.py
    

    After issuing two n commands in order for the function to get parsed (I believe this is how pdb works). You can issue a debug get_value_for_weekday(0) command to recursively step in the function:

    (Pdb) debug get_value_for_weekday(0)
    ENTERING RECURSIVE DEBUGGER
    > (1)()
    ((Pdb)) s
    --Call--
    > /home/jim/Desktop/pdbscript.py(3)get_value_for_weekday()
    -> def get_value_for_weekday(weekday_index=None):
    ((Pdb)) n
    > /home/jim/Desktop/pdbscript.py(4)get_value_for_weekday()
    -> values = [10, 20, 20, 10, 30, 30, 30]
    ((Pdb)) n 
    > /home/jim/Desktop/pdbscript.py(5)get_value_for_weekday()
    -> if not weekday_index:
    ((Pdb)) p weekday_index
    0
    ((Pdb)) n
    > /home/jim/Desktop/pdbscript.py(7)get_value_for_weekday()
    -> return sum(values) / 7
    

    Do note, I feel really sketchy about this form of meta-debugging but it seems to be what you're after.

提交回复
热议问题