Is it possible to set the python -O (optimize) flag within a script?

大兔子大兔子 提交于 2019-11-27 16:36:24

问题


I'd like to set the optimize flag (python -O myscript.py) at runtime within a python script based on a command line argument to the script like myscript.py --optimize or myscript --no-debug. I'd like to skip assert statements without iffing all of them away. Or is there a better way to efficiently ignore sections of python code. Are there python equivalents for #if and #ifdef in C++?


回答1:


-O is a compiler flag, you can't set it at runtime because the script already has been compiled by then.

Python has nothing comparable to compiler macros like #if.

Simply write a start_my_project.sh script that sets these flags.




回答2:


#!/usr/bin/env python
def main():
    assert 0
    print("tada")

if __name__=="__main__":
   import os, sys
   if '--optimize' in sys.argv:
      sys.argv.remove('--optimize')
      os.execl(sys.executable, sys.executable, '-O', *sys.argv)
   else:
      main()


来源:https://stackoverflow.com/questions/7527055/is-it-possible-to-set-the-python-o-optimize-flag-within-a-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!