Search code examples
pythonlinuxsoftware-distribution

Running multiple pythons


I recently upgraded to python 3.4 to use continuum tools but many of my scripts are written for 2.7. This can causes some errors; some are simple (like "print" now requires parentheses), but others are more complicated:

if struct.unpack("h", "\0\1")[0] == 1:
  defs.append(("WORDS_BIGENDIAN", None))

Yields the error:

  File "setup.py", line 302, in build_extensions
    if struct.unpack("h", "\0\1")[0] == 1:
    TypeError: 'str' does not support the buffer interface

Is there a way to run my python code as 2.x like you can with C++ (-std=c++11 etc) ? It's possible that many more errors will surface if I just solve this one. Thanks!


Solution

  • Python 3 is really a different language than Python 2. There's no way to make the Python 3 interpreter run Python 2 code (unless that code doesn't happen to use any of the features that were changed).

    You may want to read the guide to porting to Python 3 in the Python documentation. Here's a brief summary of the current recommendations:

    • If you only need to support Python 3 from now on (you don't need to maintain Python 2 compatibility), use the 2to3 tool to translate most of your code, then manually fix up whatever it has missed. There is lots of documentation that explains the changes between versions, if you haven't used Python 3 before.
    • If you're writing new code and need to be able to run it with both Python versions, write for Python 3 (or a common subset of 2 and 3) and backport to Python 2 as necessary.
    • If you have an existing Python 2 codebase and you want to run it on Python 3 without breaking Python 2 compatibility, use libraries like six and from future imports to help you port your code to a common subset of the two versions of Python. 2to3 and other tools like modernize will help you find the places you can improve things. Note that it's easier to make this work if you drop support for older version of Python 2.