在 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
然后
- 使用
python -O abc.py
运行
- 使用
python abc.py
运行
观察差异。
关于#ifdef DEBUG 的 Python 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13352677/