user1165419
user1165419

Reputation: 663

Why does python 2.4 keep ignoring my exit function?

I've written a script that only runs on version 2.6 or 2.7. I've placed in a safety check to see if another version is installed and to also check if there are any compatible versions available. Here is my code snippet;

# !/usr/bin/python

import sys, os, re
from sys import exit

if sys.version[0:3] in ['2.6', '2.7']:
    import subprocess, datetime, os.path, json, urllib2, socket

def python_version():

    version = sys.version[0:3]

    while version not in ['2.6', '2.7']:

        print '\n\nYou\'re using an incompatible version of Python (%s)' % version

        python_installed_version = []

        for files in os.listdir("/usr/bin/"):  # check to see version of python already on the box

            python_version = re.search("(python2(.+?)[6-7]$)", files)

            if python_version:
                python_installed_version.append(python_version.group())

        if python_installed_version:

            print 'Fortunately there are compatible version(s) installed. Try the following command(s): \n\n',

            for version in python_installed_version:
                print 'curl http://script.py  | %s\n' % version

        sys.exit()

python_version()

with p.stdout:

print 'hello'

When I run the above in python 2.4 I get this error;

  File "<stdin>", line 46
      with p.stdout:
     ^
SyntaxError: invalid syntax

I don't understand why the script doesn't exit as soon as it detects that you're using python 2.4 with sys.exit(), but instead carries on reading the script and gives the error above where the with p.stout: is read.

I have removed the with p.stdout: line, and it will work fine, it won't read the print 'hello'. I don't know why the with p.stdout: is causing the script to break. This works perfectly fine on 2.6 and 2.7.

Any ideas on why python 2.4 will still read the with p.stdout: line? Thanks.

Upvotes: 0

Views: 816

Answers (1)

viraptor
viraptor

Reputation: 34145

Python 2.4 doesn't have the with syntax support yet, so the script fails at the parsing stage, rather than at runtime. You can work around that by having some wrapper like:

if version_check_ok():
    import actual_app
    actual_app.run()
else:
    ...

This way the new files with the new syntax will not be imported/parsed until you know it's safe to do so. You can't move the import above the version check however.

Upvotes: 4

Related Questions