version

Chris Angelico rosuav at gmail.com
Fri Jun 1 21:54:40 EDT 2018


On Sat, Jun 2, 2018 at 11:34 AM, Mike McClain <mike.junk.46 at att.net> wrote:
> On Fri, Jun 01, 2018 at 08:02:27AM -0700, Mike McClain wrote:
>> On Thu, May 31, 2018 at 07:44:35PM -0700, Mike McClain wrote:
>> <snip>
>> > Is there a way in a script to know which version of python is being
>> > run so I can write:
>> >     If (version == 2.7):
>> >         do it this way
>> >     elsif (version == 3.2):
>> >         do it another way
>> >
>>
>> Thanks for the responses,
>
> Those responses were sys.version_info.major and the module 'six'.
> The first works here:
>     if( sys.version_info.major == 3 ):
>         choice = input("<CR> to continue, or <ESC> to abort")
>     else:
>         choice = raw_input("<CR> to continue, or <ESC> to abort")   #  OK in 2.7

Even better:

try: input = raw_input
except NameError: pass

and then just use input() everywhere.

> but not here:
>     if( sys.version_info.major == 3 ):
>         print( row, sep=', ')
>     else:
>         print ', '.join(row)    #   failing in 3.2
>
> Both of the above print statements throw syntax errors, one under 2.7
> the other under 3.2.

Even better:

from __future__ import print_function

and then use the version 3 style everywhere.

> I looked at 'six' and it putting wrappers around calls would mean a
> rewrite of what is basically just a playground for exploring what
> python is and certainly not worth the trouble to rewrite much.
>
> It looks like what I was wanting is something like 'C's #if, a
> compiler conditional.
>
> Does python have anything like that to tell the interpreter to ignore
> a line that is not a comment or a quoted string?

No, but for each potential problem where you'd need it, you should
have an alternative that works within the current syntax. At least so
long as the oldest version you need to support is 2.7, anyway.

I would recommend upgrading to an even newer version of Python,
incidentally. Python 3.2 is itself extremely old. I'm not sure if
there are any Wheezy backports of newer versions of Python, but when I
was using Wheezy, I just compiled my own Python 3.x from source; the
Debian-provided /usr/bin/python3 isn't touched (and probably isn't
used anyway - on Wheezy, system scripts are all using 2.7 IIRC), and
you have a new /usr/local/bin/python3 that would be a lot newer.

The newer Python versions make cross-version compatibility a LOT easier.

ChrisA



More information about the Python-list mailing list