問題描述
TypeError: непадтрымоўваны сокет тыпу аперанда Python (TypeError: unsupported operand type‑python socket)
I have been trying to fix the issue below for long time.I am trying to get a reponse like 200,401 eyc.It will be great if you could take a quick look at the code below.I tried in two different way,but none works as indicated inside the block.I will really appreciate if someone could help me.
"head="/questions/ask"
host = "stackoverflow.com"
port = 80
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
sys.stderr.write("[ERROR] %s\n" % msg[1])
sys.exit(1)
try:
sock.connect((host, port))
except socket.error, msg:
sys.stderr.write("[ERROR] %s\n" % msg[1])
sys.exit(2)
sock.send("HEAD %s HTTP/1.0\r\n\r\n")%(head)
#this one gives me error" sock.send("HEAD head1 HTTP/1.0\r\n\r\n")%(head)
TypeError: unsupported operand type(s) for %: 'int' and 'str'", my Url is string!
sock.send("HEAD head HTTP/1.0\r\n\r\n")
#gives error 404
s=sock.recv(12)
print s
sock.close()
sys.exit"
‑‑‑‑‑
參考解法
方法 1:
sock.send("HEAD %s HTTP/1.0\r\n\r\n")%(head)
should be
sock.send("HEAD %s HTTP/1.0\r\n\r\n" % head)
Does that make sense? It's an order of operations thing ‑ right now the sending happens first, returning an integer, on which you're trying to use %
for string formatting ‑ but on integers that operator gives you the modulus, which needs another number after it.
(by Robin Clarke、Thomas)