struct.error: 's' 的参数必须是 python 3.4 中的字节对象 [英] struct.error: argument for 's' must be a bytes object in python 3.4
本文介绍了struct.error: 's' 的参数必须是 python 3.4 中的字节对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在 python 3.4 中使用的代码:
Code I'm attempting to use in 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
我看到这段代码在不使用 python3 时确实有效,但我的项目需要在 3 中使用它.我尝试与问题进行比较:Struct.Error, Must Be a Bytes Object? 但我不知道如何将其应用到自己身上.
I see that this code does work when not using python3 but I need it in 3 for my project. I tried comparing to problem: Struct.Error, Must Be a Bytes Object? but I couldn't see how I can apply this to myself.
推荐答案
您需要将 ifname
字符串转换为字节.您也不需要调用 ord(),因为 ioctl 返回字节,而不是字符串:
You need to convert the ifname
string into bytes. You also don't need to call ord(), since ioctl returns bytes, not a string:
...
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]
...
见这个问题关于python3中字符串和字节的更多信息
See this SO question for more info about strings and bytes in python3
这篇关于struct.error: 's' 的参数必须是 python 3.4 中的字节对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文