[python] python: sys is not defined

I have a piece of code which is working in Linux, and I am now trying to run it in windows, I import sys but when I use sys.exit(). I get an error, sys is not defined. Here is the begining part of my code

try:
    import numpy as np
    import pyfits as pf
    import scipy.ndimage as nd
    import pylab as pl
    import os
    import heapq
    import sys
    from scipy.optimize import leastsq

except ImportError:
    print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
    sys.exit()

Why is sys not working??

This question is related to python sys

The answer is


I'm guessing your code failed BEFORE import sys, so it can't find it when you handle the exception.

Also, you should indent the your code whithin the try block.

try:

import sys
# .. other safe imports
try:
    import numpy as np
    # other unsafe imports
except ImportError:
    print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
    sys.exit()

In addition to the answers given above, check the last line of the error message in your console. In my case, the 'site-packages' path in sys.path.append('.....') was wrong.


You're trying to import all of those modules at once. Even if one of them fails, the rest will not import. For example:

try:
    import datetime
    import foo
    import sys
except ImportError:
    pass

Let's say foo doesn't exist. Then only datetime will be imported.

What you can do is import the sys module at the beginning of the file, before the try/except statement:

import sys
try:
    import numpy as np
    import pyfits as pf
    import scipy.ndimage as nd
    import pylab as pl
    import os
    import heapq
    from scipy.optimize import leastsq

except ImportError:
    print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
    sys.exit()