Python == python2 OR python == python3 ? How to package, distribute python py2k scripts

compatibilitypackagingpythonscripting

Depending on system, python==python2 or python==python3.

Executable Python scripts, starts with:

#!/usr/bin/env python
#!/usr/bin/env python2
#!/usr/bin/env python3...

For python py3k it is provided in documentation I should/can use it with version number, so I do this:

#!/usr/bin/env python3

But I've found a problem with py2k scripts.

While in py2k documentation it is written to use : #! /usr/bin/env python ,

on some *nix-es python py3k is default, so python==python3. (For example ArchLinux python package , here python package files).

How to package (configure,make) and/or prepare python scripts for distribution to handle that ?

I ask about making software packages that can be run easily by users (without modyfing their environment)

Can I do the same trick for python py2k scripts as for python py3k scripts and set it as : #!/usr/bin/env python2 ?
Can I be sure that each python py2k distribution contains python2 file, so #!/usr/bin/env python2 will work ?

If yes, why it is not proposed as standard, for example in python py2k documentation ?

Best Answer

A script can check its Python version and, if that's Python 3, re-start itself using Python 2. Add the following near the head of the script:

if sys.version > '3':
  python2 = os.popen('which python2 2> /dev/null').read().rstrip()
  if python2:
    args = sys.argv[:]
    args.insert(0,python2)
    os.execv(python2,args)
  else:
    sys.exit("%s requires Python Version 2 (python2 not in PATH)" % os.path.basename(__file__))

This uses the system's which command to locate python2 in the environment's PATH. It then relaunches itself with that (or aborts if unable to find it).

Note that the script does need to be valid Python 3 syntax for it to start in Python 3.

Also, any output should be flushed before the execv call or it will be lost. Adding, for example, sys.stdout.flush() just before the call to execv will flush any print statements.

Related Question