awesomo awesomo - 6 months ago 40
Bash Question

How to fix shebang flags that are not recognized on some systems

For some reason, the

-O
(optimized) flag is not recognized in the shebang line on a Red Hat Enterprise Server (release 5.3) that I access. On other systems, the flag is recognized without any issue.

Executing the script below on OS X works fine. Recognition of the
-O
flag can be verified because it enables (when absent) or disables (when given) anything under the
if __debug__
conditional:

#!/usr/bin/env python -O

if __name__ == '__main__':

if __debug__:
print 'lots of debugging output on'

print 'Fin'


Executing the same script on the RHE system result in:


/usr/bin/env: python -O: No such file
or directory


Without the
-O
flag, the script executes normally on the RHE system (i.e., the
__debug__
built-in variable will be set to
True
).

Is there a cross-platform way to fix this issue? Is there even a platform-specific way to fix the issue of flags on the shebang line to the python interpreter?

Edit: Any other workarounds to setting the
__debug__
variable (without using shebang flags) interpreter-wide would also be interesting.

Answer

How about making a small shell script:

pythono:

#!/bin/sh    
/usr/bin/env python -O "$@"

Then change your script to use:

#!pythono       

Also note that setting the environment variable PYTHONOPTIMIZE to a non-empty string is the same as using the -O flag. From the man python man page:

   PYTHONOPTIMIZE
          If this is set to a non-empty string it is equivalent to  specifying  the
          -O option. If set to an integer, it is equivalent to specifying -O multiā€
          ple times.
Comments