【问题标题】:Unknown format code 'x' [duplicate]未知格式代码“x”[重复]
【发布时间】:2016-07-19 15:29:14
【问题描述】:

我正在使用 Python 编写一个程序,所有代码看起来都不错,除非我从终端运行程序时收到以下错误消息:

Traceback (most recent call last):
  File "packetSniffer.py", line 25, in <module>
    main()
  File "packetSniffer.py", line 10, in main
    reciever_mac, sender_mac, ethernetProtocol, data = ethernet_frame(rawData)
  File "packetSniffer.py", line 17, in ethernet_frame
    return getMacAddress(reciever_mac), getMacAddress(sender_mac), socket.htons(protocol), data[14:]
  File "packetSniffer.py", line 21, in getMacAddress
    bytesString = map('{:02x}'.format, bytesAddress)
ValueError: Unknown format code 'x' for object of type 'str'

到目前为止,这是我整个程序的代码,有人可以帮忙吗?

import struct
import textwrap
import socket

def main():
    connection = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))

    while True:
        rawData, address = connection.recvfrom(65535)
        reciever_mac, sender_mac, ethernetProtocol, data = ethernet_frame(rawData)
        print('\nEthernet Frame: ')
        print('Destination: {}, Source: {}, Protocol: {}'.format(reciever_mac, sender_mac, ethernetProtocol))

# Unpack ethernet frame
def ethernet_frame(data):
    reciever_mac, sender_mac, protocol = struct.unpack('! 6s 6s H', data[:14])
    return getMacAddress(reciever_mac), getMacAddress(sender_mac), socket.htons(protocol), data[14:]

# Convert the Mac address from the jumbled up form from above into human readable format
def getMacAddress(bytesAddress):
    bytesString = map('{:02x}'.format, bytesAddress)
    macAddress = ':'.join(bytesString).upper()
    return macAddress

main()

【问题讨论】:

标签: python python-3.x


【解决方案1】:

在以下代码部分中,format type x 不需要字符串。它接受整数。然后它将整数转换为其对应的十六进制形式。

# Convert the Mac address from the jumbled up form from above into human readable format
def getMacAddress(bytesAddress):
    bytesString = map('{:02x}'.format, bytesAddress)
    macAddress = ':'.join(bytesString).upper()

所以如果你的 bytesAddress 是整数的字符串形式,那么,你可以这样做:

bytesAddress = '123234234'
map('{:02x}'.format, [int(i) for i in bytesAddress])
#map('{:02x}'.format, map(int, bytesAddress)) 
['01', '02', '03', '02', '03', '04', '02', '03', '04']

另外,如果你想将一对整数(字符串形式)处理成十六进制,那么首先将`bytesAddress转换成

[bytesAddress[i:i+2] for i in range(0, len(bytesAddress), 2)]

【讨论】:

  • 你可以使用python 3来摆脱这个错误。
猜你喜欢
  • 1970-01-01
  • 2014-07-03
  • 2015-12-23
  • 2016-06-28
  • 1970-01-01
  • 2013-12-14
  • 2021-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多