#ifdef DEBUG 的 Python 等效项

标签 python debugging

在 C 中,我们编写如下代码

#ifdef DEBUG
printf("Some debug log... This could probably be achieved by python logging.Logger");
/* Do some sanity check code */
assert someCondition
/* More complex sanitycheck */
while(list->next){
assert fooCheck(list)
}

#endif

有没有办法在 python 中做到这一点?

编辑:我得到了答案,还有更多:) Paolo、Steven Rumbalski 和 J Sebastian 为我提供了我正在寻找的信息。感谢 das 的详细回答,尽管我现在可能不会使用预处理器。

J Sebastian,他的评论被删除了,因为他发表评论的答案,我认为删除了他的答案。 他说我可以使用 Logger 中的 isEnabledFor() 方法来提供条件。

感谢大家的投入。这是我的第一个问题。我希望我能接受 paolo 或 j sebastian 的回答。但由于这些是作为评论提供的,我会接受 das 的回答。

我可能会使用 http://nestedinfiniteloops.wordpress.com/2012/01/15/if-debug-python-flavoured/或 Logger.isEnabledFor()

最佳答案

在您的代码中使用 __debug__:

if __debug__:
    print 'Debug ON'
else:
    print 'Debug OFF'

用上面的代码创建一个脚本abc.py然后

  1. 使用 python -O abc.py
  2. 运行
  3. 使用 python abc.py
  4. 运行

观察差异。

关于#ifdef DEBUG 的 Python 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13352677/

相关文章:

c - printf 期间出现访问冲突错误

visual-studio - 在VS2005/2008中自动化 "Attach to Process"

netbeans - 如何在 NetBeans IDE 中调试 Clojure?

.net - 可移植 .Net 调试工具

Notepad++ 的 C++ 调试器

python - Pandas : using both log and stack on a bar plot

Python 类 - 使用实例作为属性

python - 为什么我们需要在 surface.blit() 之后进行 display.update() 操作?

python - 如何在python中编辑拼接模块的opencv源代码?

python - 通过比较两列来跟踪 Pandas 中的状态反转