简体   繁体   English

如何调试代码和可视化执行

[英]How to debug code and visualize the execution

I'm taking open-source class.我正在使用开源 class。 I am given doctests and a CLI to test my code and see if it passes, however, how can I visualize my code to see what is happening?我得到了 doctests 和 CLI 来测试我的代码并查看它是否通过,但是,我如何可视化我的代码以查看发生了什么? For instance, I am having a hard time understanding how the for loop is working and I would like to see what list is assigned in each recursion.例如,我很难理解for loop是如何工作的,我想看看在每个递归中分配了哪些列表。

The file has many functions so running -m doctest isn't ideal and also doesn't show the execution.该文件具有许多功能,因此运行-m doctest并不理想,也不会显示执行情况。 When I run debug mode in vs code and set a breakpoint at the function, it never steps into the function.当我在 vs 代码中运行调试模式并在 function 处设置断点时,它永远不会进入 function。 I imagine this is because in the file I never call nut_finder() but I don't want to start adding to the source code since that would defeat the purpose of the doctest.我想这是因为在文件中我从不调用nut_finder()但我不想开始添加到源代码,因为这会破坏 doctest 的目的。 I can also run python interactively but that too won't show me how the code is executing.我也可以交互式地运行 python 但这也不会告诉我代码是如何执行的。

The only solution I have found is to use a tool that visualizes the code, however, this requires me to manually copy and paste stuff.我找到的唯一解决方案是使用可视化代码的工具,但是,这需要我手动复制和粘贴内容。 This also will become a problem from large applications and multi-file applications.这也将成为大型应用程序和多文件应用程序的问题。 So in short, how can I learn the right way to debug my code.简而言之,我怎样才能学习调试代码的正确方法。

# lab05.py
def nut_finder(t):
"""Returns True if t contains a node with the value 'nut' and
False otherwise.

>>> scrat = tree('nut')
>>> nut_finder(scrat)
True
>>> sproul = tree('roots', [tree('branch1', [tree('leaf'), tree('nut')]), tree('branch2')])
>>> nut_finder(sproul)
True
>>> numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])
>>> nut_finder(numbers)
False
>>> t = tree(1, [tree('nut',[tree('not nut')])])
>>> nut_finder(t)
True
"""
if label(t) == 'nut':
    return True
for b in branches(t):
    if nut_finder(b):
        return True
return False

I think python 3.7 and up: type breakpoint() right where you want it to stop.我认为 python 3.7 及更高版本:在您希望它停止的地方键入breakpoint() It is a shortcut for using pdb module ( https://docs.python.org/3/library/pdb.html ).它是使用 pdb 模块的快捷方式( https://docs.python.org/3/library/pdb.html )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM