[Python] Relative shebang: How to write an executable script running portable interpreter...

Discussão em 'Python' iniciado por Stack, Fevereiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    Let's say we have a program/package which comes along with its own interpreter and a set of scripts which should invoke it on their execution (using shebang).

    And let's say we want to keep it portable, so it remains functioning even if simply copied to a different location (different machines) without invoking setup/install or modifying environment (PATH). A system interpreter should not be mixed in for these scripts.

    The given constraints exclude both known approaches like shebang with absolute path:

    #!/usr/bin/python


    and search in the environment

    #!/usr/bin/env python


    Separate launchers look ugly and are not acceptable.

    I found good summary of the shebang limitations which describe why relative path in the shebang are useless and there cannot be more than one argument to the interpreter: http://www.in-ulm.de/~mascheck/various/shebang/

    And I also found practical solutions for most of the languages with 'multi-line shebang' tricks. It allows to write scripts like this:

    #!/bin/sh
    "exec" "`dirname $0`/python2.7" "$0" "$@"
    print copyright


    But sometimes, we don't want to extend/patch existing scripts which rely on shebang with an absolute path to interpreter using this approach. E.g. Python's setup.py supports --executable option which basically allows to specify the shebang content for the scripts it produces:

    python setup.py build --executable=/opt/local/bin/python


    So, in particular, what can be specified for --executable= in order to enable the desired kind of portability? Or in other words, since I'd like to keep the question not too specific to Python...

    The question


    How to write a shebang which specifies an interpreter with a path which is relative to the location of the script being executed?

    Continue reading...

Compartilhe esta Página