How can I use python interpreter option “-O” on python executable file(exe)?

I made python exe file by pyinstaller using –onefile option. And I want to use interpreter options like “-O” on my python exe file. Because my python scripts include debug flags.

Below is simplification of my code structure.

# main.py
import sys

if __name__ == '__main__':
    lastIndex = len(sys.argv) - 1
    value1 = sys.argv[lastIndex-1]
    value2 = sys.argv[lastIndex]

    if __debug__:
        print('{} {}'.format(value1, value2))

I got main.exe using

pyinstaller --onefile main.py

I tried to execute main.exe with -O option on cmd, and it looks like debug flag wasn’t affected by “-O”

> main.exe -O value1 value2

What can I do for this?

Answer

The documentation says

PyInstaller can be run with Python optimization flags (-O or -OO) by executing it as a Python module, rather than using the pyinstaller command:

# run with basic optimizations
python -O -m PyInstaller myscript.py 
# also discard docstrings
python -OO -m PyInstaller myscript.py 

Or, by explicitly setting the PYTHONOPTIMIZE environment variable to a non-zero value.