Wrap the part of your code that needs Spatial Analyst extension as follows

`arcpy.CheckOutExtension("spatial")
your code
arcpy.CheckInExtension("spatial")`

By checking out licenses only when you need them and checking them in, you won't hold up licences if other people need to use them. This is useful in a setting where there are fewer licenses than the people who use them in a network environment.