1

I would like to check if my interpreter is using Python 3, before parsing the entire file, to print a decent error message otherwise.

In this question, there is an answer regarding Python 2.4 / 2.5. However, when I tried to reproduce the solution in my Python 2.7 / 3.3 environment, it did not work.

For instance, running the following file:

try:
  eval("print('', end='')")
except SyntaxError:
  raise Exception("python 3 needed")

print("", end="")

Results in the following error:

File "test_version.py", line 6
  print("", end="")
             ^
SyntaxError: invalid syntax

That is, eval is not evaluated soon enough to prevent the parser from reaching line 6.

Is there another hack that might work here?

Community
  • 1
  • 1
DanGar
  • 113
  • 2
  • The code posted here would not work on Python 2.4 or 2.5 either; you are using `print()` as a function in the code, so the compiler will throw the exception anyway. Move the `print()` use *out* of this module into a separate module. – Martijn Pieters Feb 10 '14 at 10:32

2 Answers2

2

The classic way to check for the version of Python that is running your script is to use the tuple returned by sys.version_info (http://docs.python.org/2/library/sys.html):

from __future__ import print_function
import sys
if sys.version_info[0] < 3:
    print("This program needs Python version 3.2 or later")
    sys.exit(1)

The reason to enable print() as a function through the import from __future__ is because the script wouldn't parse under Python 3.x if the print statement was used.

Apalala
  • 9,017
  • 3
  • 30
  • 48
  • Could you explain your answer? – everton Feb 10 '14 at 17:00
  • @EvertonAgner Using `sys.version_info` will give you information about the version of Python you are using. This is how you can determine if you are using a version you need - just as a general tip. – 2rs2ts Feb 10 '14 at 17:19
1

Move code using print() as a function to a separate module and make the main script do the testing only.

It doesn't matter where in the module the print() function call is made, it is a syntax error because you are not using print as a statement. You'd put that in a separate module imported after your test.

try:
    eval("print('', end='')")
except SyntaxError:
    raise Exception("python 3 needed")

import real_script_using_print_function

However, in Python 2 you can also add:

from __future__ import print_function

at the top to make print() work in Python 2 as well. It is perfectly feasible to write Python code that runs on both Python 2 and 3 if taken care.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • The `from __future__ import print_function` is exactly what I needed. I cannot add another "main" file to replace the current one, but I can add the import and then test the version without errors. – DanGar Feb 10 '14 at 11:08