python实现类似C/C++的条件编译

python实现条件编译


python中的一个内置常量 __debug__ ,该常量默认是 True ,但是在执行python脚本时加上 -O 会那么该变量就为 False 。利用这个变量可以完成类似 C/C++的条件编译
Example:

"""Example.py"""

if __name__ == "__main__":
    if not __debug__ :
        print("This is a debug test")
    else :
        print("This is a usual test")
..$ python3 Example.py
This is a usual test
..$ python3 -O Example.py
This is a debug test

尽管有点麻烦,还是能完成测试。

你可能感兴趣的:(python,python)