python调试代码

    科技2022-08-04  107

    python调试代码

    Professional programmers will throw chairs at you when you tell them you use print() to hunt down errors. Is there any point diving down the stack-trace hole with a full debug setup as a beginner? Some say yes because you might as well learn it from the start. I say, “Whatever gets the job done.”

    当您告诉专业程序员使用print()来查找错误时,专业程序员将为您服务。 在初学者使用完整调试设置的情况下,还有什么要深入堆栈跟踪Kong的吗? 有人说“是”,因为您最好从一开始就学它。 我说:“无论完成什么工作。”

    I’m not saying you shouldn’t learn to read errors — that’s something different. When you are fiddling around on your own or you wish to create small snippets for others, do you need to debug like a pro? As a happy hobby programmer, you might not need to debug “properly” in your entire programmer life.

    我并不是说您不应该学习阅读错误-有所不同。 当您自己摆弄或想为他人创建小片段时,是否需要像专家一样进行调试? 作为一个快乐的业余程序员,您可能不需要在整个程序员的生活中进行“适当”的调试。

    打印或不打印 (To Print or Not to Print)

    Most code will, at some point, need debugging. Fortunately for us, there are several ways to debug your code without going into full developer mode.

    在某些时候,大多数代码都需要调试。 对我们来说幸运的是,有几种方法可以调试代码而无需进入完整的开发人员模式。

    Let’s start by looking at how print can help you debug your code.

    让我们先来看看打印如何帮助您调试代码。

    打印() (print())

    print() will give you an instant visual representation of what you are working on. If you know what output you are looking for, you will see it right there in the terminal. If it’s correct, move on. If not, dig deeper.

    print()将为您提供正在处理的内容的直观视图。 如果您知道要查找的输出,则可以在终端上看到它。 如果正确,请继续。 如果没有,请深入研究。

    Here is an example using print():

    这是使用print()的示例:

    greek_gods = ['Zeus','Poseidon','Apollo','Bob']greek_gods_only = [god for god in greek_gods if god!='Bob']gods = ','.join(greek_gods_only)

    How do you know if you managed to kick Bob out of the party?

    您怎么知道您是否成功将Bob踢出派对?

    print(gods) Bob has left the party 鲍勃离开了聚会

    Now that Bob has left the party, we can have a look at another real-life example.

    鲍勃(Bob)离开聚会之后,我们可以看看另一个真实的例子。

    I recently wrote a tool in Autodesk Maya handling cameras. In an animation scene, I needed to list all the shot cameras and leave Maya’s default cameras out of the equation. Lucky for us, Maya already defined the default cameras (startupCamera = True). This way they are are easy to find.

    我最近在Autodesk Maya中编写了一个处理相机的工具。 在动画场景中,我需要列出所有拍摄的摄像机,并将Maya的默认摄像机排除在公式之外。 对我们来说幸运的是,Maya已经定义了默认摄像机( startupCamera = True )。 这样,它们很容易找到。

    face cameras… 脸部相机...

    As you can see, there are still some unwanted cameras here, the top three face cameras from some referenced files. Now that I have seen the error with my own eyes, I can kill them by adding:

    如您所见,这里仍然有一些不需要的相机,一些参考文件中前三名的面部相机。 现在,我已经亲眼目睹了错误,现在可以通过添加以下内容消除错误:

    and ‘face’ not in cam

    and 'face' not in cam

    beautiful 美丽

    Without printing to check what the output was, I would have sent the code through the pipeline. An error email would be sent back, and we would have spent some time tracking it down. The error is not obvious, because it is a logical error and not an error that stops the code from running.

    如果不打印来检查输出是什么,我将通过管道发送代码。 错误电子邮件将被发回,我们将花费一些时间来跟踪它。 该错误不明显,因为它是逻辑错误,而不是使代码无法运行的错误。

    Printing saves money!

    打印省钱!

    调试替代方案 (Debugging Alternatives)

    OK, so you want to further explore your options. You like printing, but you realize it’s always good to expand your horizon and add weapons to your arsenal.

    好的,所以您想进一步探索您的选择。 您喜欢打印,但是您意识到扩大视野并为武器库增加武器总是很好的。

    Let’s have a look at some other ways to debug your code. Hopefully, you will find a new favorite (or just keep printing)

    让我们看看其他一些调试代码的方法。 希望您会找到一个新的收藏夹(或者只是继续打印)

    Python导师 (Python Tutor)

    Python Tutor is a simple and visual approach. This service will let you run your code and return a visual representation of what your code does, step by step.

    Python Tutor是一种简单直观的方法。 该服务将使您逐步运行代码并返回可视化表示形式。

    Let’s look at a crazy advanced function. Add the code and click Visualize Execution.

    让我们看一个疯狂的高级功能。 添加代码,然后单击“可视化执行”。

    When you do this, you will be able to step through your code one line at a time. The code is on the left, the output is on the right.

    当您这样做时,您将能够一次单行执行代码。 代码在左侧,输出在右侧。

    Here you can see the final step in this program (step 9). Line 4 sum_input(10,10) ran, and you can see the return value and the function that returns it listed on the right-hand side.

    在这里,您可以看到该程序的最后一步(步骤9)。 第4 sum_input(10,10)运行了sum_input(10,10) ,您可以在右侧看到返回值和返回该值的函数。

    Python Tutor is a quick and visual way to check your code. Python Tutor是一种快速直观的检查代码的方法。

    断言 (Assert)

    “Assertions are simply boolean expressions that check if the conditions return true or not. If it is true, the program does nothing and move to the next line of code. However, if it’s false, the program stops and throws an error.” — programiz

    “断言只是布尔表达式,用于检查条件是否返回true。 如果为真,则该程序不执行任何操作,然后移至下一行代码。 但是,如果它为假,程序将停止并引发错误。” — programiz

    Here is a simple example using assert:

    这是一个使用assert的简单示例:

    def sum_input(input_a, input_b): return input_a + input_bassert sum_input(2,3) == 5assert sum_input(2,3) != 5 AssertionError showing us that 2+3 is indeed 5 AssertionError向我们显示2 + 3确实是5

    With assert, you can check if your code does what you expect it to do. In the code above, you expect the code to return 5; that’s why you use this code which returns True.

    使用assert ,您可以检查您的代码是否达到了预期的效果。 在上面的代码中,您希望代码返回5; 这就是为什么您使用此代码返回True 。

    assert sum_input(2,3) == 5

    assert sum_input(2,3) == 5

    Then there is this code:

    然后是这段代码:

    assert sum_input(2,3) != 5

    assert sum_input(2,3) != 5

    2 + 3 can’t be anything else but 5, and therefore you expect an error (which you get). Change the code to

    2 + 3不能是5,而是其他任何东西,因此您会期望得到一个错误(得到)。 将代码更改为

    assert sum_input(2,3) != 6 or anything but 5, and you get no errors.

    assert sum_input(2,3) != 6或除5以外的任何值,都不会出错。

    Since you are the one provoking these errors, it would be weird if there were no errors, right? Try this to clean the code:

    由于您是引发这些错误的人,因此如果没有错误,那将很奇怪,对吗? 试试这个来清理代码:

    def sum_input(input_a, input_b): return input_a + input_bassert sum_input(2,3) == 5assert sum_input(2,3) != 6 The program runs like Usain Bolt in the Olympics 该程序在奥运会中像Usain Bolt一样运行

    You can create your own error messages:

    您可以创建自己的错误消息:

    assert sum_input(2,3) != 5, '2+3 is 5...Stop this nonsense'

    托尼 (Thonny)

    I was recently introduced to Thonny and instantly fell in love. Thonny is a simple IDE that provides an internal debugger. This debugger will show you everything that is going on in your code. It offers superb simplicity and a brilliant debugger.

    我最近被介绍给Thonny,并立即坠入爱河。 Thonny是提供内部调试器的简单IDE。 该调试器将向您显示代码中正在进行的所有操作。 它提供了卓越的简单性和出色的调试器。

    Let’s take a look at this code example. The program checks all the files that live in the same folder as the Python program. Then it returns a list with a tuple: (‘filename’, ‘extension’).

    让我们看一下此代码示例。 该程序检查与Python程序位于同一文件夹中的所有文件。 然后,它返回一个带有元组的列表:( ('filename', 'extension') 。

    Thonny will let you know if your code looks correct or not. Here we can see the code running with the returned results:

    Thonny会告诉您代码是否正确。 在这里,我们可以看到运行带有返回结果的代码:

    A code section, a shell section, and an Assistant section 代码部分,外壳程序部分和助手部分 Successfully returning the filenames and extensions in the folder 成功返回文件夹中的文件名和扩展名

    If we intentionally add an error, like renaming search_path to searchc_path, we can see the Assistant presenting some amazing feedback.

    如果我们有意添加一个错误,例如将search_path重命名为searchc_path ,我们可以看到Assistant提供了一些令人惊奇的反馈。

    clicking the line 8 link in the Assistant highlights the error. 单击助手中的第8行链接会突出显示该错误。

    The Assistant also gives us several hints so it will be easier for us to troubleshoot. If we expand “Did you misspell it (somewhere)?” Thonny shows us similar names. It is obvious where the error is.

    助手还会为我们提供一些提示,以便我们更轻松地进行故障排除。 如果我们展开“您是否在某个地方拼错了?” 托尼给我们看了类似的名字。 错误在哪里很明显。

    Thank you, Assistant. Now I know where my error is. 谢谢助理 现在我知道我的错误在哪里。

    If you enter debug mode, Thonny will go through the code step by step and show you everything that happens in the code.

    如果您进入调试模式,Thonny将逐步检查代码,并向您显示代码中发生的所有事情。

    debug mode 调试模式

    It stops on line 24, the if statement.

    它在if语句的第24行停止。

    Highlighting section 突出显示部分 Letting us know what the if statement asks for 让我们知道if语句的要求 __name__ __name__ Is it ‘__main__’? 是“ __main__”吗? Do they match? 他们匹配吗? Yes, they do. Run main() 是的,他们有。 运行main()

    pdb — Python的内置调试器 (pdb — Python’s Built-In Debugger)

    If you’re more into terminal dancing, Python comes with a built-in debugger known as pdb. The advantage of using pdb is that you don’t end up with print functions everywhere in your code. You can also check functions, check variables, and test your code live without editing the source. This way you are not destroying your code just because you need to test several cases.

    如果您更喜欢终端跳舞,Python会提供一个称为pdb的内置调试器。 使用pdb的优点是,您不会在代码中到处都使用打印功能。 您还可以在不编辑源代码的情况下检查函数,检查变量并实时测试代码。 这样,您就不会因为需要测试几种情况而破坏代码。

    Simply add breakpoint() to your code to let the interpreter know where you wish to enter debug mode. If you are not on a newer version of Python (3.X) you have to add the line import pdb; pdb.set_trace().

    只需在代码中添加breakpoint()即可让解释器知道您希望在何处进入调试模式。 如果您未使用较新版本的Python(3.X),则必须添加以下行: import pdb; pdb.set_trace() import pdb; pdb.set_trace() 。

    To read more about pdb, head over to the documentation.

    要了解有关pdb更多信息,请转至文档 。

    Real Python also has a good tutorial series on the debugger.

    Real Python在调试器上也有不错的教程系列。

    结论 (In Conclusion)

    Printing is no substitute for proper debugging. It is by no means valid in a workplace with a developer team, but it can work fine for a beginner programmer. I think there are a lot more printer people out there than we know. It’s quick and you’ll know what the expected output should be. It gives you visual feedback in seconds.

    打印不能代替适当的调试。 这绝对不是在有开发人员团队的工作场所中有效的方法,但是对于初学者来说,它可以正常工作。 我认为那里的打印机人员比我们知道的要多。 快速,您将知道预期的输出是多少。 它可以在几秒钟内为您提供视觉反馈。

    If you wish to have a look at the alternatives to debug your code, please give it a go. Maybe you’ll find a new way that works better for you.

    如果您希望了解调试代码的替代方法,请尝试一下。 也许您会找到一种更适合您的新方法。

    If you wish to keep printing, I honestly think you should, as long as you are allowed to by your lead developers.

    如果您希望继续打印,老实说,只要您的主要开发人员允许,您就应该这样做。

    翻译自: https://medium.com/better-programming/ignore-the-professionals-debug-your-python-code-using-print-2579301edb2b

    python调试代码

    相关资源:微信小程序源码-合集6.rar
    Processed: 0.012, SQL: 8