0
votes

I have a socket server program:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Author:sele


import socket

HOST = '127.0.0.1'
PORT = 65432

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data:
                break

            conn.sendall(data)

when I run it in my terminal:

there get error:

sele-MacBook-Pro:test01 ldl$ ./tests02-server.py
Traceback (most recent call last):
File "./tests02-server.py", line 11, in
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
AttributeError: exit

why there get this error?

2
You are using Python 2.x, I suppose? Socket objects didn't get the context manager functionality needed to support with until 3.x.jasonharper
I see that the above is the example code from the Python 3.x documentation for the socket class. As jasonharper says, that doesn't work in Python 2.x. The "#!/usr/bin/env python" hashbang line defaults to Python2, so if both Python2 and Python3 are installed, you'll get Python2. The hashbang line should read "#!/usr/bin/env python3".Dave Rove

2 Answers

1
votes

You can't use socket.socket(socket.AF_INET, socket.SOCK_STREAM) with with. So that a with statement can clean up the resource it is working with, that resource's object has to have an __exit__ method. What socket.socket(socket.AF_INET, socket.SOCK_STREAM) returns obviously has no __exit__ method for with to call, hence this error.

Per @jasonharper, it sounds like this would work if you were using Python3. Maybe you copied Python3 code from somewhere, but are running Python 2.7?

1
votes

You probably already figured this out, but if you run the script from terminal in the following manner, you will not get the error: ~$ python3 echo-server.py