How to use command line arguments with shebang /usr/bin/env python

Last Modified: Thu, 25 Jul 2013 14:49:45 +0000 ; Created: Thu, 25 Jul 2013 14:49:45 +0000

A lot of Python scripts for Unix systems have a starting line like:

#!/usr/bin/env python

This allows more portable support to ensure the python interpreter can be found without having to specify an absolute path that may be different depending on the OS distribution. E.g. not having to use /usr/bin/python or /usr/local/bin/python, etc.

The problem is if you want to add parameters (e.g. python -tt) you will get an error like "/usr/bin/env: python -tt: No such file or directory" due to how the OS parses the shebang line arguments and passes them to the env program.

The solution:

#!/bin/sh
''':'
exec python -tt "$0" "$@"
'''
# The above shell shabang trick is more portable than /usr/bin/env and supports adding arguments to the interpreter (python -tt)

The '' is just an empty string ignored by /bin/sh. : means noop to /bin/sh. Python sees the ''' as just a docstring so it effectively ignores the shebang line.