How to Fix Except Error Python in Linux

When I was running a Python script on my Linux system, I ran into a strange syntax error. It confused me at first because the code looked perfectly fine. But then I realized the problem I was running Python 2 style code with Python 3. If you’ve ever seen the dreaded SyntaxError pointing at an except line, then you know exactly what I mean.

Problem Code

Here’s the exact snippet that triggered the error for me:

def search(self):
    message = ''
    result_count = 0
    gip = pygeoip.GeoIP('GeoLiteCity.dat')
    ip = self.ip_textbox.text()
    try:
        ip = socket.gethostbyname(str(ip))
        message = "Host: %s Is Currently Available" % (str(ip))
    except socket.error, e:   #  invalid in Python 3
        message = "Host: %s Is Currently Unavailable" % (str(ip))
    
    result_count += 1
    msg_box("SeArCh CoMpLeTe", "%d Results Were Found For %s" % (result_count, str(ip)))

    except Exception, e:      #  invalid in Python 3
        msg_box("", str(e))

    msg_box("Search Complete", "No Results Were Found For %s" % (str(ip)))
    return

The Error Explain

When I tried running it, Linux immediately complained:

File "pygeo_ip.py", line 142
    except Exception, e:
         ^ 
SyntaxError: invalid syntax

Here’s why:

  • In Python 2, you could write: except Exception, e:
  • But in Python 3, the correct syntax is: except Exception as e:

Since most Linux distributions now default to Python 3 (running python usually points to Python 3.6+), this mismatch breaks the script.

Fix Code (Python 3)

Once I changed the exception syntax, everything worked again. Here’s the corrected version:

import socket
import pygeoip

def search(self):
    message = ''
    result_count = 0
    gip = pygeoip.GeoIP('GeoLiteCity.dat')
    ip = self.ip_textbox.text()

    try:
        ip = socket.gethostbyname(str(ip))
        message = "Host: %s is currently available" % (str(ip))
    except socket.error as e:   #  Python 3 syntax
        message = "Host: %s is currently unavailable (%s)" % (str(ip), str(e))

    result_count += 1
    msg_box("Search Complete", "%d results were found for %s" % (result_count, str(ip)))

    try:
        # some risky code here
        pass
    except Exception as e:      #  Python 3 syntax
        msg_box("Error", str(e))

    return message

Now the script runs without syntax errors.

Added Practice Functionality

Since I was already in the code, I decided to add some extra features to make it more useful:

  • Reverse DNS Lookup – to show the hostname.
  • GeoIP Lookup – to show the city and country.
  • Graceful Results – so the program still works if something goes wrong.

Here’s my improved version:

import socket
import pygeoip

def search(self):
    message = ''
    result_count = 0
    gip = pygeoip.GeoIP('GeoLiteCity.dat')
    ip = self.ip_textbox.text()

    try:
        ip_addr = socket.gethostbyname(str(ip))
        hostname = socket.gethostbyaddr(ip_addr)[0]
        geo_data = gip.record_by_addr(ip_addr)

        message = (
            f"Host: {ip_addr} ({hostname}) is currently available.\n"
            f"Location: {geo_data['city']}, {geo_data['country_name']}"
        )
    except socket.error as e:
        message = f"Host {ip} is unavailable. Error: {str(e)}"
    except Exception as e:
        message = f"Unexpected error occurred: {str(e)}"

    result_count += 1
    msg_box("Search Results", f"{result_count} result(s) for {ip}:\n{message}")
    return message

This way, not only do I know whether the host is available, but I also get its hostname and even its location.

Key Takeaways

Here’s what I learned (and you can avoid the same headaches):

  1. Always use except Exception as e: in Python 3.
  2. Linux usually defaults to Python 3, so old Python 2 code needs updating.
  3. Adding extra functionality like GeoIP lookup and reverse DNS makes scripts more practical.
  4. Good exception handling prevents unexpected crashes and gives useful error messages.

Final Thought

At first, I was frustrated by that SyntaxError, but it turned out to be a great learning moment. Fixing the except syntax not only solved the problem but also encouraged me to improve the project with extra functionality. If you’re running into the same error on Linux, don’t panic it’s just the difference between Python 2 and Python 3.

Related blog posts