首页 > 解决方案 > TypeError:str() 最多接受 1 个参数(给定 2 个)并且 TypeError:需要一个整数

问题描述

我正在尝试通过http://myipaddr:50997/notExisted.html访问不存在的文件类型, 但出现以下错误。有人可以向我解释吗?


    from socket import *
    serverPort = 50997

    serverSocket = socket(AF_INET, SOCK_STREAM)         

    serverSocket.bind(("", serverPort))

    serverSocket.listen(1)

    # Server should be up and running and listening to the incoming    connections
    while True:
    print ("Ready to serve...")

        # Set up a new connection from the client
        connectionSocket, addr = serverSocket.accept()

        try:
            # Receives the request message from the client
            message =  connectionSocket.recv(1024)
            print ("Message is: "), message

            filename = message.split()[1]
            print ("File name is: "), filename

            f = open(filename[1:])

            outputdata = f.read()
            connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n")

    for i in range(0, len(outputdata)):  
        connectionSocket.send(outputdata[i])
    connectionSocket.send("\r\n")

    # Close the client connection socket
    connectionSocket.close()

except IOError:
    # Send HTTP response message for file not found
    connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n")
    connectionSocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n")
    # Close the client connection socket
    connectionSocket.close()

    serverSocket.close() 

我得到的错误。

connectionSocket.send(bytes("HTTP/1.1 404 Not Found\r\n\r\n","UTF-8"))
TypeError: str() takes at most 1 argument (2 given)

当我尝试删除 bytes(); 时出现此错误

Traceback (most recent call last):
  File "tcpServer.py", line 26, in <module>
    connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n","UTF-8")
TypeError: an integer is required

标签: pythonsockets

解决方案


需要整数的错误消息有点令人困惑,因为您可以.send()使用bytes参数调用,因此您走在了正确的轨道上。

但是,您调用bytes("HTTP/1.1 404 Not Found\r\n\r\n","UTF-8"), 即带有两个参数。您不需要为bytes()演员提供编码,bytes("HTTP/1.1 404 Not Found\r\n\r\n")就足够了。

如果要指定编码,请改用:

"HTTP/1.1 404 Not Found\r\n\r\n".encode('UTF-8')

IE:

connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n".encode("UTF-8"))

推荐阅读