Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: __exit__ with socketserver on python-3.4.3

I have two systems

  1. A Mac system running python 3.6.3
  2. A linux (ubuntu 14.04) sytem running python 3.4.3

I've been testing the following code segment on both systems to try and identify the cause of a bug on the ubuntu system.

import urllib.request
import http.server
import socketserver
PORT = 8000

def requestHandler(request, client_address,server):
    # test to print to console when the handler is invoked. 
    print("Request = " + str(request) + " Client Address = " + str(client_address) + " Server = " + str(server))

def startWebServer():
    Handler = requestHandler
    with socketserver.TCPServer(("", PORT), Handler) as httpd:
        print("serving at port", PORT)
        httpd.serve_forever()

def main():
    startWebServer()

main()

On the Mac this works as expected, invoking the requestHandler and printing information to the console.

However, on the ubuntu system I receive the following error.

Traceback (most recent call last):
  File "sockettest.py", line 19, in <module>
    main()
  File "sockettest.py", line 17, in main
    startWebServer()
  File "sockettest.py", line 12, in startWebServer
    with socketserver.TCPServer(("", PORT), Handler) as httpd:
AttributeError: __exit__

I am suspecting that I have misconfigured the ubuntu python installation.

Could you suggest what I might have done wrong?

like image 913
Simon Avatar asked Jan 26 '26 04:01

Simon


1 Answers

socketserver servers don't support use as context managers before Python 3.6. Quoting the docs:

Changed in version 3.6: Support for the context manager protocol was added. Exiting the context manager is equivalent to calling server_close().

In the future, if different Python versions are behaving differently, you should check the docs to look for documented version differences.

like image 169
user2357112 supports Monica Avatar answered Jan 28 '26 17:01

user2357112 supports Monica