Python导入模块但在我启动它时却无法识别它?

时间:2016-01-07 23:24:44

标签: python sockets

老实说,我不知道为什么会发生这种情况,我认为由于它没有进行堆栈交换,所以我犯了一个非常错误的错误。所以这里出现了错误:

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) UnboundLocalError:局部变量' socket'在分配前引用

tcpServer.py

import socket

def Main():
    UID = 1001
    sockets = []
    users = [] ## create usernames list
    sessionLimit = input("session Queue Limit: ")

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('192.168.1.74', 12127))

    s.listen(sessionLimit) ## listen for 1 connection at a time

    while True:
        c, addr = s.accept()
        sockets.append(c)
        users.append(c.recv(1024).decode('utf-8'))
        print("Connection from " + str(addr))

        data = c.recv(1024).decode('utf-8') ## recieve 1024 bytes from client at a time, and then decode it into utf-8
        if not data:
            break

        temp == data
        temp.split(" ") 
        if temp[0] == "//": ## check to see if user has sent command
            if temp[1] == "msg":
                for i in range(len(users)):
                    if users[i] == temp[2]:
                        sockets[i].send((" ".join(temp[::2])).encode('utf-8'))
        else: ## else, send data to all users. Could just use s.sendall(data.encode('utf-8'))
            for socket in sockets:
                socket.send(data.encode('utf-8')) ## send to sockets[socket]

        ##print("From connected user: " + data)
        ##data = data.upper()
        ##print("Sending: " + data)
        ##c.send(data.encode('utf-8'))

        ## command listening
        commands = input("-> ")
        commands.split(" ")

        if commands[0] == "exit":
            c.close() ## close connection
        elif commands[0] == "/msg":
            for i in range(len(users)):
                if users[i] == commands[1]:
                    sockets[i].send((" ".join(commands[::1])).encode('utf-8'))
    """
       elif commands[0] == "/rename": ## dont implement yet, due to users[] length changing
            for i in range(len(users)):
                if users[i] == commands[1]:
                    sockets[i].send("<server_" + UID + "> rename " + commands[2].encode('utf-8'))
        """
    c.close()

    if __name__ == "__main__":
        Main()

感谢您的帮助! - 雅各布

1 个答案:

答案 0 :(得分:1)

问题是当您执行以下代码块时,您在socket函数的上下文中使用变量名Main()

    for socket in sockets:
        socket.send(data.encode('utf-8')) ## send to sockets[socket]

这导致了socket库的命名问题。如果您将其更改为:

    for sock in sockets:
        sock.send(data.encode('utf-8')) ## send to sockets[socket]

它将开始工作。我还必须以不同方式缩进您的代码,以确保它完全在您设置的Main()函数中,并且必须确保将input()解析为int。作为参考,这里是为我工作的完整代码块:

import socket

def Main():
    UID = 1001
    sockets = []
    users = [] ## create usernames list
    sessionLimit = int(input("session Queue Limit: "))

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('192.168.1.74', 12127))
    s.listen(sessionLimit) ## listen for 1 connection at a time

    while True:
        c, addr = s.accept()
        sockets.append(c)
        users.append(c.recv(1024).decode('utf-8'))
        print("Connection from " + str(addr))

        data = c.recv(1024).decode('utf-8') ## recieve 1024 bytes from client at a time, and then decode it into utf-8
        if not data:
            break

        temp == data
        temp.split(" ") 
        if temp[0] == "//": ## check to see if user has sent command
            if temp[1] == "msg":
                for i in range(len(users)):
                    if users[i] == temp[2]:
                        sockets[i].send((" ".join(temp[::2])).encode('utf-8'))
        else: ## else, send data to all users. Could just use s.sendall(data.encode('utf-8'))
            for sock in sockets:
                sock.send(data.encode('utf-8')) ## send to sockets[socket]

        ##print("From connected user: " + data)
        ##data = data.upper()
        ##print("Sending: " + data)
        ##c.send(data.encode('utf-8'))

        ## command listening
        commands = input("-> ")
        commands.split(" ")

        if commands[0] == "exit":
            c.close() ## close connection
        elif commands[0] == "/msg":
            for i in range(len(users)):
                if users[i] == commands[1]:
                    sockets[i].send((" ".join(commands[::1])).encode('utf-8'))
        """
        elif commands[0] == "/rename": ## dont implement yet, due to users[] length changing
            for i in range(len(users)):
                if users[i] == commands[1]:
                    sockets[i].send("<server_" + UID + "> rename " + commands[2].encode('utf-8'))
        """
    c.close()

if __name__ == "__main__":
    Main()