报错name ‘AF_INET‘ is not defined。/TypeError: ‘module‘ object is not callable

Generally, the name'xxx' is not defined means that xxx is not defined. It is likely that the variable is not defined before the variable is used, or the local variable is referenced globally.
Here we refer to the tsTserv3.py or tsTserv.py file in the python core programming, the error message is
as follows:
8 ADDR = (HOST,PORT)
9
—> 10 tcpSerSock=socket(AF_INET,SOCK_STREAM) #AF_INET is Ipv4
11 tcpSerSock. bind(ADDR)
12 tcpSerSock.listen(5)

NameError: name ‘AF_INET’ is not defined
或者如下:
8 ADDR = (HOST,PORT)
9
—> 10 tcpSerSock=socket(AF_INET,SOCK_STREAM)
11 tcpSerSock.bind(ADDR)
12 tcpSerSock.listen(5)

TypeError:'module' object is not callable
here is likely to write the first sentence as import socket, and change it to from socket import *. The complete code is as follows:

#import socket
from socket import *
from time import *

HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)

tcpSerSock=socket(AF_INET,SOCK_STREAM)  #AF_INET即Ipv4
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)

while True:
    print('waiting for connection...')
    tcpCliSock,addr = tcpSerSock.accept()
    print('...connect from:',addr)
    while True:
        data = tcpCliSock.recv(BUFSIZ)
        if not data:
            break
        tcpCliSock.send('[%s] %s' %(bytes(ctime(), 'utf-8'),data))
        
    tcpCliSock.close()
tcpSerSock.close()
        

Check the information and understand that the difference between the two is quite big.
Here, the difference between import and form xx import *:
     mainly for the
      import socket of the socket module, socket.AF_INET will report an error saying that there is no AF_INET family because of the value of AF-INET In the socket namespace, from socket import * is to introduce all the names under the socket into the current namespace.

First of all:
import: can modify the properties of the object, regardless of whether the object is mutable.
from xx import *: Only modifiable module objects are mutable types, and immutable types cannot be modified.
Second, the usage is different:
1. import: import xx, take import time and a created python class as an example: when calling the method in the time module, you need to add time.; and when calling the method in the class, you also need Add the instance name aa in front.
2. from XX import *: In this way, you can call directly.

For example, the correct operation is as shown in the following figure: Insert picture description here
three characteristics are different
1. import: all imported classes need to be restricted by the module name when used.
2. from XX import *: All imported classes do not need to add restrictions.
Part of reference Baidu know

Guess you like

Origin blog.csdn.net/qq_45701131/article/details/108432358