Why is this shell script calling itself as python script?
Question: Obviously this shell script is calling itself as a Python script:

    
    
    #!/bin/sh
    ## repo default configuration
    ##
    REPO_URL='git://android.git.kernel.org/tools/repo.git'
    REPO_REV='stable'
    
    magic='--calling-python-from-/bin/sh--'
    """exec" python -E "$0" "$@" """#$magic"
    if __name__ == '__main__':
      import sys
      if sys.argv[-1] == '#%s' % magic:
        del sys.argv[-1]
    del magic
    :
    :
    

(Whole script: <http://android.git.kernel.org/repo>)

Can anyone explain

  * the purpose of calling it this way?  
Why not having `#!/usr/bin/env python` in the first line so it gets
interpreted as Python script from the beginning?

  * the purpose of adding that magic last command line argument, that is removed afterwards in the beginning of the Python code? 


Answer: Your first question: this is done to fix unix systems (or emulations thereof)
that do not handle the #! correctly or at all. The high art is to make a
script that is coreect in shell as well as in the other language. For perl,
one often sees something like:

    
    
    exec "/usr/bin/perl"
       if 0;
    

The exec is interpreted and executed by the shell, but the perl interpreter
sees a conditional statetment (.... if ...) and does nothing because the
condition is false.

