Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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++?

like image 851
hobs Avatar asked Sep 23 '11 09:09

hobs


2 Answers

-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.

like image 191
Jochen Ritzel Avatar answered Nov 14 '22 01:11

Jochen Ritzel


#!/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()
like image 41
jfs Avatar answered Nov 14 '22 02:11

jfs