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

后端 未结 2 1509
小蘑菇
小蘑菇 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:04

    With regards to your example, you don't need to exit pdb and change the code. You can step into the function (with 's') and set weekday_index=0 inside.

    One solution to your original problem is to use the debugger's jump command as follows:

    1. jump before the function call using 'j #line-number'
    2. step in the function with 's'
    3. set the input params, and continue debugging.

    This worked when I tried it, but the debugger complained when I tried to do step 3 before step 2 for some reason.

    0 讨论(0)
  • 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
    > <string>(1)<module>()
    ((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.

    0 讨论(0)
提交回复
热议问题