疑难解答“TypeError:ord() 预期的长度为 1 的字符串,但找到了 int”
Posted
技术标签:
【中文标题】疑难解答“TypeError:ord() 预期的长度为 1 的字符串,但找到了 int”【英文标题】:Troubleshooting "TypeError: ord() expected string of length 1, but int found" 【发布时间】:2013-11-22 17:09:34 【问题描述】:ERROR : TypeError: ord() expected string of length 1, but int found
我在编译程序时遇到此错误。
File "C:\Users\Administrator\Desktop\tracer1.py", line 129, in <module>
get_route("www.google.com")
File "C:\Users\Administrator\Desktop\tracer1.py", line 85, in get_route
d = build_packet()
File "C:\Users\Administrator\Desktop\tracer1.py", line 62, in build_packet
myChecksum = checksum(header + data)
File "C:\Users\Administrator\Desktop\tracer1.py", line 28, in checksum
thisVal = ord(str[count+1]) * 256 + ord(str[count])
**TypeError: ord() expected string of length 1, but int found**
程序是使用ICMP查找traceroute
from socket import *
import socket
import os
import sys
import struct
import time
import select
import binascii
import ctypes
ICMP_ECHO_REQUEST = 8
MAX_HOPS = 30
TIMEOUT = 2.0
TRIES = 2
# The packet that we shall send to each router along the path is the ICMP echo
# request packet, which is exactly what we had used in the ICMP ping exercise.
# We shall use the same packet that we built in the Ping exercise
ctypes.windll.shell32.IsUserAnAdmin()
print (ctypes.windll.shell32.IsUserAnAdmin())
def checksum(str):
csum = 0
countTo = (len(str) / 2) * 2
count = 0
while count < countTo:
thisVal = ord(str[count+1]) * 256 + ord(str[count])
csum = csum + thisVal
csum = csum & 0xffffffff
count = count + 2
if countTo < len(str):
csum = csum + ord(str[len(str) - 1])
csum = csum & 0xffffffff
csum = (csum >> 16) + (csum & 0xffff)
csum = csum + (csum >> 16)
answer = ~csum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def build_packet():
# In the sendOnePing() method of the ICMP Ping exercise ,firstly the header of our
# packet to be sent was made, secondly the checksum was appended to the header and
# then finally the complete packet was sent to the destination.
# Make the header in a similar way to the ping exercise.
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
myChecksum = 0
pid = os.getpid() & 0xFFFF
# Make a dummy header with a 0 checksum.
# struct -- Interpret strings as packed binary data
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, pid, 1)
#header = struct.pack("!HHHHH", ICMP_ECHO_REQUEST, 0, myChecksum, pid, 1)
data = struct.pack("d", time.time())
# Calculate the checksum on the data and the dummy header.
# Append checksum to the header.
myChecksum = checksum(header + data)
if sys.platform == 'darwin':
myChecksum = socket.htons(myChecksum) & 0xffff
#Convert 16-bit integers from host to network byte order.
else:
myChecksum = htons(myChecksum)
packet = header + data
return packet
def get_route(hostname):
timeLeft = TIMEOUT
for ttl in range(1,MAX_HOPS):
for tries in range(TRIES):
destAddr = socket.gethostbyname(hostname)
#Fill in start
# Make a raw socket named mySocket
mySocket = socket.socket(AF_INET, SOCK_RAW, getprotobyname("icmp"))
mySocket.bind(("", 12000));
#Fill in end
mySocket.setsockopt(socket.IPPROTO_IP, socket.IP_TTL, struct.pack('I', ttl))
mySocket.settimeout(TIMEOUT)
try:
d = build_packet()
mySocket.sendto(d, (hostname, 0))
t = time.time()
startedSelect = time.time()
whatReady = select.select([mySocket], [], [], timeLeft)
howLongInSelect = (time.time() - startedSelect)
if whatReady[0] == []: # Timeout
print ("* * * Request timed out.")
recvPacket, addr = mySocket.recvfrom(1024)
print ("addr")
timeReceived = time.time()
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
print ("* * * Request timed out.")
except socket.timeout:
continue
else:
#Fill in start
# Fetch the icmp type from the IP packet
print( struct.calcsize("bbHHhd"))
request_code, request_type, checksum, packet_id, \
sequence, timeSent, data = struct.unpack("bbHHhd", recvPacket,0)
#Fill in end
if request_type == 11:
bytes = struct.calcsize("d")
timeSent = struct.unpack("d", recvPacket[28:28 + bytes])[0]
print (" %d rtt=%.0f ms %s" % (ttl,(timeReceived -t)*1000, addr[0]))
elif request_type == 3:
bytes = struct.calcsize("d")
timeSent = struct.unpack("d", recvPacket[28:28 + bytes])[0]
print (" %d rtt=%.0f ms %s" % (ttl,(timeReceived -t)*1000, addr[0]))
elif request_type == 0:
bytes = struct.calcsize("d")
timeSent = struct.unpack("d", recvPacket[28:28 + bytes])[0]
print (" %d rtt=%.0f ms %s" % (ttl,(timeReceived -timeSent)*1000, addr[0]))
return
else:
print ("error")
break
finally:
mySocket.close()
get_route("www.google.com")
【问题讨论】:
莫名其妙!如果可以重现,请尝试在checksum()
的开头打印repr(str)
。
【参考方案1】:
您正在使用 Python 3 运行脚本,其中索引 bytes
对象返回一个整数:
>>> b"abc"[1]
98
删除ord()
调用。在这种情况下,它们是多余的。
【讨论】:
猜得好!如果他们正在运行 Python3,他们还应该更改(len(str) / 2) * 2
以使用整数除法(或者简单地将 &
去掉最后一位)。
@TimPeters 你能解释清楚吗,有什么需要改变的。
@user2977469 使用 //
而不是 /
进行整数除法 - 它也适用于最新版本的 Python 2。
例如,在 Python 3 中,“3/2”是“1.5”。您的 checksum()
函数希望它返回整数 1(这发生在 Python 2 中)。最快的解决方法是将countTo = (len(str) / 2) * 2
中的/
更改为//
。如果不这样做,您的函数将无法正常处理奇数长度的字符串。
@user2977469:你删除了ord
电话吗?【参考方案2】:
我今天遇到了类似类型的错误。我在此处添加了此答案以突出某些观察结果。这里要关注的主要 API 是 triple_des
。如果输入是qqq
,那么就会报错。如果输入为sMAC
,则没有错误。有趣的是,qqq == sMAC
是 true
。此外,通过binascii
打印的两个变量都显示出相似的值。变量qqq
来自bytearray.fromhex('7A414086D86A4BF5554AE6FBC4AC0465')
,变量sMAC
来自"7A414086D86A4BF5554AE6FBC4AC0465",decode('hex')
。
>>> qqq[0]
122
>>> sMAC[0]
'z'
>>> qqq == sMAC
True
>>> binascii.hexlify(sMAC)
'7a414086d86a4bf5554ae6fbc4ac0465'
>>> binascii.hexlify(qqq)
'7a414086d86a4bf5554ae6fbc4ac0465'
>>> qqq == sMAC
True
>>> repr(qqq)
"bytearray(b'zA@\\x86\\xd8jK\\xf5UJ\\xe6\\xfb\\xc4\\xac\\x04e')"
>>> repr(sMAC)
"'zA@\\x86\\xd8jK\\xf5UJ\\xe6\\xfb\\xc4\\xac\\x04e'"
>>> cipher1 = triple_des(qqq,CBC,"\0\0\0\0\0\0\0\0",pad=None,padmode=PAD_PKCS5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 710, in __init__
self.setKey(key)
File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 727, in setKey
self._padding, self._padmode)
File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 409, in __init__
self.setKey(key)
File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 414, in setKey
self.__create_sub_keys()
File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 462, in __create_sub_keys
key = self.__permutate(des.__pc1, self.__String_to_BitList(self.getKey()))
File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 421, in __String_to_BitList
data = [ord(c) for c in data]
TypeError: ord() expected string of length 1, but int found
>>> cipher1 = triple_des(sMAC,CBC,"\0\0\0\0\0\0\0\0",pad=None,padmode=PAD_PKCS5)
>>>
希望这个额外的细节有所帮助。
【讨论】:
以上是关于疑难解答“TypeError:ord() 预期的长度为 1 的字符串,但找到了 int”的主要内容,如果未能解决你的问题,请参考以下文章