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++?
Asked
Active
Viewed 2,669 times
12

hobs
- 18,473
- 10
- 83
- 106
2 Answers
13
-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.

Jochen Ritzel
- 104,512
- 31
- 200
- 194
8
#!/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()

jfs
- 399,953
- 195
- 994
- 1,670
-
3That's because you got the wrong arguments to `os.execl()`. The second argument is `arg0` not `arg1`. Try using `os.execl(sys.executable, sys.executable, '-O', *sys.argv)` or in fact pretty much any other string for the second argument and it should work as you expect. – Duncan Sep 23 '11 at 12:50
-
@Duncan: I've fixed the arguments. – jfs Sep 23 '11 at 13:40
-
Great work-around! I never want to run without '-OO', so I made it into `if __debug__: os.execl(sys.executable, sys.executable, '-OO', *sys.argv)` instead – Mads Y Nov 20 '17 at 18:05