Rya*_*yan 23
Python的编译方式与C或C++甚至Java不同,python文件是"动态"编译的,您可以将其视为类似于Basic或Perl等解释语言.1
只需使用if语句,就可以完成与条件编译等效的操作.例如:
if FLAG:
    def f():
        print "Flag is set"
else:
    def f():
        print "Flag is not set"
您可以对创建类,变量设置和几乎所有内容执行相同的操作.
模仿IFDEF的最接近的方法是使用hasattr函数.例如:
if hasattr(aModule, 'FLAG'):
    # do stuff if FLAG is defined in the current module.
您还可以使用try/except子句来捕获名称错误,但惯用的方法是在脚本顶部将变量设置为None.
DNS*_*DNS 19
实际上有一种获得条件编译的方法,但它非常有限.
if __debug__:
    doSomething()
该__debug__标志是一个特例.使用-O或-OO选项调用python时,__debug__将为false,编译器将忽略该语句.这主要用于断言,这就是为什么如果你真的用优化编译你的脚本,断言就会消失.
因此,如果您的目标是添加调试代码,但防止它减慢速度或以其他方式影响"发布"版本,这可以满足您的需求.但是你不能分配一个值__debug__,所以你可以使用它.
Eva*_*ice 13
也可以在PYPI(Python包索引)上找到它,并且可以使用pip获取.
使用的基本示例是:
from pypreprocessor import pypreprocessor
pypreprocessor.parse()
#define debug
#ifdef debug
print('The source is in debug mode')
#else
print('The source is not in debug mode')
#endif
您还可以通过指定...将后处理代码输出到文件中
pypreprocessor.output = 'output_file_name.py'
pypreprocessor导入和对parse()的调用之间的任何地方.
该模块本质上是C预处理器条件编译的python实现.
SideNote:这与python2x和python 3k兼容
免责声明:我是pypreprocessor的作者
更新:
我以前忘了提.与其他答案中描述的if/ else或if _debug:方法不同,这是一个真正的预处理器.生成的字节码不包含有条件排除的代码.
| 归档时间: | 
 | 
| 查看次数: | 19184 次 | 
| 最近记录: |