Klik Klik - 4 months ago 24
Python Question

Is there a way to force a Python program to run in version 2.7?


I have some Python scripts which use libraries only available to Python 2.7 and so I want to be able to run those in Python version 2.7.

I was thinking that it would be great if I could put some code at the top of my Python file which would detect if it was being run in Python 3 and if so execute itself in version 2.7. Is this possible?

For example, the pseudo code would be:

if (self.getPythonVersion != 2.7):
os.execute('python27 ' + os.cwd + 'script.py')

Edit: This is for my personal use, not for distributing.


I used mgilson's answer below to get this to work for me. I was not able to get os.exec() to work, but I didn't spend a long time on that. The second script worked for me. Here is what I used and worked for me:

if sys.version_info[:2] > (2, 7):
code = subprocess.call(['python27', sys.argv[0] ])
raise SystemExit(code)


Nope, this isn't possible for the simple reason that a user could have python3.x installed and not have python2.x installed.

If you know that they have python2.7 installed, then you can use something like your work-around above, however, in that case, you'll have to make sure that you can support both python3.x and python2.x in the same source (which is generally a non-trivial task)

You can detect the python version via sys.version_info and I think you can swap out the process using something in the os.exec* family of functions... e.g.:

import os, sys

if sys.version_info[:2] > (2, 7):
    os.execve('python27', sys.argv, os.environ)

Here's another variant that you can try (it'll create a new process instead of replacing the old one however):

import sys, subprocess

if sys.version_info[:2] > (2, 7):
    code = subprocess.call(['python27'] + sys.argv)
    raise SystemExit(code)