-1

I have this non-portable shebang:

#!/usr/bin/env python -u

It is non portable because python -u is fed as one single arg to env on my system.

Challenge: make this shebang portable changing the shebang only - that is to say a one-liner.

In other words, no solutions

1
  • I asked for a solution involving the shebang line only, not a multi-line solution.
    – dnozay
    Oct 11, 2013 at 4:45

1 Answer 1

11

I'd use the following:

#!/bin/sh
"""true"
exec python -u "$0" "$@"
"""
# python code goes here

The line """true" will be parsed by sh as true, because it consists of an empty "" string followed by "true". Since true is a no-op command, it will be effectively ignored, and the following line will execute the Python interpreter.

On the other hand, Python will parse the """true" line very differently, as the opening of a triple-quoted string which starts with true" and is closed two lines below. Since the string is not used for anything, the Python interpreter will effectively ignore the shell snippet that starts up Python. It is the difference in interpretation of """xxx" that allows Python and sh code coexist in the same script.

For a simple test, append something like:

import sys
print "hello!", sys.argv

Given a reasonable sh implementation (and taking into account the time to start Python), this should not be measurably slower than using env.

6
  • 4
    +1 That's dirty, but somehow satisfying
    – user2363448
    Oct 10, 2013 at 19:37
  • One drawback is that the hack will be treated as part of (if not the entirety) of the script's docstring.
    – chepner
    Oct 10, 2013 at 20:08
  • @chepner Is this a problem in practice? Docstrings of importable modules are quite useful, but I can't think of a use for docstrings in executable scripts. Oct 10, 2013 at 20:11
  • pydoc displays the contents of the module docstring as the description of the script.
    – chepner
    Oct 10, 2013 at 20:16
  • Couldn't you continue to add to the end of the docstring? Oct 10, 2013 at 20:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.