struct.error: 's' 的参数必须是 python 3.4 中的字节对象

Pam*_*m B 4 python networking

我试图在 python 3.4 中使用的代码:

#!/usr/bin/python3
 def get_mac_addr(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', ifname[:15]))
    return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]
 print (get_mac_addr('eth0'))

Error: struct.error: argument for 's' must be a bytes object
Run Code Online (Sandbox Code Playgroud)

我看到这段代码在不使用 python3 时确实有效,但我的项目需要在 3 中使用它。我尝试与问题进行比较:Struct.Error, Must Be a Bytes Object? 但我不知道如何将其应用到自己身上。

pbk*_*hrv 5

您需要将ifname字符串转换为字节。您也不需要调用 ord(),因为 ioctl 返回字节,而不是字符串:

...
info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', bytes(ifname[:15], 'utf-8')))
return ''.join(['%02x:' % b for b in info[18:24]])[:-1]
...
Run Code Online (Sandbox Code Playgroud)

有关python3 中字符串和字节的更多信息,请参阅此 SO 问题