user7693832
user7693832

Reputation: 6849

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: get error: AttributeError: __exit__

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?

Upvotes: 1

Views: 8546

Answers (2)

user12728684
user12728684

Reputation: 41

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

Upvotes: 4

CryptoFool
CryptoFool

Reputation: 23079

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?

Upvotes: 5

Related Questions