1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2004
    Rep Power

    Running new code with old Python versions

    I would like to make sure that people running my Python script are using a proper version of Python.

    For example:

    #!/usr/bin/env python1.5
    import sys
    if sys.version[:3] < 2.1:
        print "You are using an old version of python."
    def bla():
        a += 3
    When running this code, Python tells me that it found some 'invalid syntax'.
    So, it seems that Python is first parsing the whole file and complaining about things it does not understand and then starting execution.

    How to perform such a check correctly?

    Thank you, B.
  2. #2
  3. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Cambridge, UK
    Rep Power
    My guess is that you are failing at

    a += 3

    which of course is not a form that works in early versions (the += operator was not present). You must not use code that cannot be compiled by earlier versions.

    The easiest solution is to have your version checking code in a separate module that imports the main code only when the version is correct.

    If your program must run with all version of Python then don't use the modern stuff! If you want to make use of language improvements only use operators common to all versions and have conditional imports and excecution of code based on the version of Python.


IMN logo majestic logo threadwatch logo seochat tools logo