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

被刻印的时光 ゝ 提交于 2019-12-01 05:25:07

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!