您可以通过运行来达到您所描述的效果.pyc
file directly与-O
旗帜。这是对事物应有的运作方式的滥用。您想要:
- Run the
.py
文件有或没有-O
标志(通常的方法),或
- Run the
.pyc
file without the -O
旗帜,或
- Run the
.pyo
file with the -O
flag.
如果你运行一个.pyc
文件与-O
标志,或.pyo
没有它的文件,你会得到像这样的惊喜。
发生的情况是,在编译时,窥视孔优化器已经优化掉了if __debug__
分支,所以.pyc
or .pyo
文件将无条件执行适当的分支。然后当你跑错了-O
规范,您将以以下值运行__debug__
这与编译时应用的优化不匹配。
有一个类似问题 http://bugs.python.org/issue8379不久前报告了 Python 问题跟踪器,尽管情况相反:有人运行.pyo
文件而不使用-O
flag.
一个简单的例子:假设我的当前目录中有一个类似于您的文件,名为“debug_example.py”:
noether:Desktop mdickinson$ cat debug_example.py
def main():
print "__debug__ is {}".format(__debug__)
if __debug__:
print "__debug__ is True"
else:
print "__debug__ is False"
if __name__ == '__main__':
main()
如果我们直接执行该文件,无论有没有-O
flag,我们看到了预期的结果:
noether:Desktop mdickinson$ python2 debug_example.py
__debug__ is True
__debug__ is True
noether:Desktop mdickinson$ python2 -O debug_example.py
__debug__ is False
__debug__ is False
现在让我们使用方便的方法将此文件编译为“debug_example.pyc”文件py_compile http://docs.python.org/library/py_compile.html模块。 (在你的情况下,这个编译可能是作为setup.py
安装。):
noether:Desktop mdickinson$ python2 -m py_compile debug_example.py
noether:Desktop mdickinson$ ls -l debug_example.pyc
-rw-r--r-- 1 mdickinson staff 350 24 Mar 21:41 debug_example.pyc
现在我们执行debug_example.pyc
文件,但(错误地)使用-O
标志,Python 会感到困惑:
noether:Desktop mdickinson$ python2 -O debug_example.pyc
__debug__ is False
__debug__ is True
我们可以用蟒蛇的dis module http://docs.python.org/2/library/dis.html查看模块内的字节码:
Python 2.7.6 (default, Nov 18 2013, 15:12:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import debug_example
>>> import dis
>>> dis.dis(debug_example)
Disassembly of main:
2 0 LOAD_CONST 1 ('__debug__ is {}')
3 LOAD_ATTR 0 (format)
6 LOAD_GLOBAL 1 (__debug__)
9 CALL_FUNCTION 1
12 PRINT_ITEM
13 PRINT_NEWLINE
4 14 LOAD_CONST 2 ('__debug__ is True')
17 PRINT_ITEM
18 PRINT_NEWLINE
19 LOAD_CONST 0 (None)
22 RETURN_VALUE
请注意,没有对应的字节码if
那里的声明:我们看到无条件打印'__debug__ is True'
.
解决办法:不要执行.pyc
or the .pyo
直接文件:执行.py
文件并让 Python 判断是否使用.pyc
or .pyo
作为适当的。