0

I try to check if current version is 3 and if so, switch to python2:

#!/usr/bin/python

import sys, os

if sys.version_info[0] != 2:
    os.execl("/usr/bin/", "python2", *sys.argv)

print(sys.version_info[:])

But this script returns this error:

Traceback (most recent call last):
  File "./a.py", line 6, in <module>
    os.execl("/usr/bin/", "python2", *sys.argv)
  File "/usr/lib/python3.3/os.py", line 531, in execl
    execv(file, args)
PermissionError: [Errno 13] Permission denied

What have I missed?

pradyunsg
  • 18,287
  • 11
  • 43
  • 96
ciembor
  • 7,189
  • 13
  • 59
  • 100

2 Answers2

2

os.execl("/usr/bin/", "python2", *sys.argv)

/usr/bin/ is a directory, you can't run it. Try:

os.execl("/usr/bin/python2", "/usr/bin/python2", *sys.argv[1:])

user9876
  • 10,954
  • 6
  • 44
  • 66
0

I would argue what you are attempting is a bad idea - it is surprising behaviour and not needed, instead, simply use an explicit hashbang:

#!/usr/bin/python2

Or, preferably:

#!/usr/bin/env python2

As per PEP 394, any unix system should provide python2.

Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
  • Well, that's the point - python doesn't have python2 symlink in OSX. – ciembor Jan 22 '13 at 10:47
  • @ciembor Then I would recommend contacting the maintainer of that package and suggesting they fix that bug. The PEP is quite clear - *"Unix-like software distributions (including systems like Mac OS X and Cygwin) should install the python2 command into the default path whenever a version of the Python 2 interpreter is installed, and the same for python3 and the Python 3 interpreter."*. – Gareth Latty Jan 22 '13 at 10:47