5

I'm using the new print from Python 3.x and I observed that the following code does not compile due to the end=' '.

from __future__ import print_function

import sys
if sys.hexversion < 0x02060000:
    raise Exception("py too old")

...
print("x",end=" ") # fails to compile with py24

How can I continue using the new syntax but make the script fails nicely? Is it mandatory to call another script and use only safe syntax in this one?

Craig McQueen
  • 41,871
  • 30
  • 130
  • 181
sorin
  • 161,544
  • 178
  • 535
  • 806
  • 2
    If we could send a guy back in time, we might convince Guido to add a nice pragma "__minimum_python_version__(2,0)" – Warren P Jul 09 '10 at 20:40

3 Answers3

8

The easy method for Python 2.6 is just to add a line like:

b'You need Python 2.6 or later.'

at the start of the file. This exploits the fact that byte literals were introduced in 2.6 and so any earlier versions will raise a SyntaxError with whatever message you write given as the stack trace.

Scott Griffiths
  • 21,438
  • 8
  • 55
  • 85
2

There are some suggestions in this question here, but it looks like it is not easily possible. You'll have to create a wrapper script.

Community
  • 1
  • 1
Mad Scientist
  • 18,090
  • 12
  • 83
  • 109
2

One way is to write your module using python 2.x print statement, then when you want to port it into python 3, you use 2to3 script. I think there are scripts for 3to2 conversion as well, although they seems to be less mature than 2to3.

Either way, in biggers scripts, you should always separate domain logic and input/output; that way, all the print statements/functions are bunched up together in a single file. For logging, you should use the logging module.

Lie Ryan
  • 62,238
  • 13
  • 100
  • 144
  • 2
    The entire idea is to write Python 3 ready code that will work with 2.6+ python not to do plan to do switch in the future. – sorin Jun 14 '10 at 13:59