www.rodneybeede.com "I would love to change the world, but they won't give me the source code" - unknown
 Navigation

How to use command line arguments with shebang /usr/bin/env python - Last Modified 2013-07-25 14:49 UTC - Created 2013-07-25 14:49 UTC

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" "[email protected]"
'''
# 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.