Search code examples
pythonscriptingportabilityshebang

Is "python2" / "python3" safe on a script's shebang?


Sometimes I see #!/usr/bin/python2 and #!/usr/bin/python3 as opposed to simply #!/usr/bin/python. I get the appeal of this approach, you get to explicitly say if you need Python 2 or 3 without doing some weird version checking.

Are these python2 and python3 standard though? Will they work everywhere? Or is it risky?

I just confirmed I have python2 and python3 but I am on Cygwin so I wouldn't think this means it's necessarily the same for a lot of others.


Note: To anyone considering #!/usr/bin/python with or without a number, a more important thing to remember is that python isn't even always in /usr/bin (FreeBSD and OSX for example), so use #!/usr/bin/env python if you want to most portability.

Then just pray that env is in /usr/bin.


Solution

  • As a single point of reference -- I don't have a python2 executable on my system:

    $ python2
    -bash: python2: command not found
    

    So I would definitely not consider this one to be portable. Obviously I could still run your script by selecting an executable explicitly:

    python2.7 your_script.py
    

    Or by symlinking python2 to python2.7, but the point is that it won't work out of the box for me (and I imagine for a number of other users as well).