So, I started learning to code in Python and later Django. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?

我通常只使用Django启用时提供的调试信息。当事情确实像我想象的那样结束时,我用一个语法错误破坏了代码流,并查看流中那个点的变量,以找出代码在哪里做了与我想要的不同的事情。

但这种情况还能改善吗?是否有一些更好的工具或方法来调试Django代码?


当前回答

在开发过程中,快速添加

assert False, value

可以帮助诊断视图或其他任何地方的问题,而不需要使用调试器。

其他回答

我使用pyDev与Eclipse真的很好,设置断点,进入代码,查看任何对象和变量的值,尝试它。

我使用PyCharm(与eclipse相同的pydev引擎)。真的帮助我能够直观地逐级检查我的代码,并看到发生了什么。

调试Django代码的最佳选择之一是通过wdb: https://github.com/Kozea/wdb

wdb works with python 2 (2.6, 2.7), python 3 (3.2, 3.3, 3.4, 3.5) and pypy. Even better, it is possible to debug a python 2 program with a wdb server running on python 3 and vice-versa or debug a program running on a computer with a debugging server running on another computer inside a web page on a third computer! Even betterer, it is now possible to pause a currently running python process/thread using code injection from the web interface. (This requires gdb and ptrace enabled) In other words it's a very enhanced version of pdb directly in your browser with nice features.

安装并运行服务器,并在代码中添加:

import wdb
wdb.set_trace()

作者认为,pdb的主要区别是:

For those who don’t know the project, wdb is a python debugger like pdb, but with a slick web front-end and a lot of additional features, such as: Source syntax highlighting Visual breakpoints Interactive code completion using jedi Persistent breakpoints Deep objects inspection using mouse Multithreading / Multiprocessing support Remote debugging Watch expressions In debugger code edition Popular web servers integration to break on error In exception breaking during trace (not post-mortem) in contrary to the werkzeug debugger for instance Breaking in currently running programs through code injection (on supported systems)

它有一个很棒的基于浏览器的用户界面。一种使用的乐趣!:)

我使用PyCharm并一直支持它。我花了一点钱,但我不得不说我从中得到的好处是无价的。我尝试过从控制台调试,我确实很信任那些能做到这一点的人,但对我来说,能够直观地调试我的应用程序是很棒的。

我不得不说,PyCharm确实占用了很多内存。但话说回来,生活中没有什么好东西是免费的。他们刚刚发布了最新版本3。它也可以很好地与Django, Flask和谷歌AppEngine一起使用。所以,总而言之,我认为这是任何开发人员都可以拥有的一个非常方便的工具。

如果你还没有使用它,我建议你试用30天,看看PyCharm的强大功能。我相信还有其他可用的工具,比如Aptana。但我想我也喜欢PyCharm的外观。我觉得在那里调试我的应用程序很舒服。

有时,当我想在一个特定的方法中探索,而召唤pdb太麻烦时,我会补充:

import IPython; IPython.embed()

IPython.embed()会启动一个IPython shell,它可以从你调用它的地方访问局部变量。