TypeError:str()最多使用1个参数(给定2个,TypeError:需要一个整数)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
")
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.send("
")
# 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
")
connectionSocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html>
")
# Close the client connection socket
connectionSocket.close()
serverSocket.close()
我得到的错误。
connectionSocket.send(bytes("HTTP/1.1 404 Not Found
","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
","UTF-8")
TypeError: an integer is required
答案
需要整数的错误消息有点令人困惑,因为您可以使用.send()
参数调用bytes
,因此您处在正确的位置。
但是,您调用bytes("HTTP/1.1 404 Not Found
","UTF-8")
,即带有两个参数。您无需为bytes()
类型转换提供编码,bytes("HTTP/1.1 404 Not Found
")
就足够了。
如果要指定编码,请改用此:
"HTTP/1.1 404 Not Found
".encode('UTF-8')
即:
connectionSocket.send("HTTP/1.1 404 Not Found
".encode("UTF-8"))
以上是关于TypeError:str()最多使用1个参数(给定2个,TypeError:需要一个整数)的主要内容,如果未能解决你的问题,请参考以下文章
TypeError: module.__init__() 最多接受 2 个参数(给定 3 个)
TypeError: function() 参数 1 必须是代码,而不是 str
TypeError:get_weather()不接受任何参数(给定1个)[关闭]
TypeError:strptime()参数1必须是str,而不是datetime.date Python