【问题标题】:struct.error: argument for 's' must be a bytes object in python 3.4struct.error: 's' 的参数必须是 python 3.4 中的字节对象
【发布时间】:2014-12-10 00:01:44
【问题描述】:

我尝试在 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?,但我不知道如何将其应用于自己。

【问题讨论】:

    标签: python networking


    【解决方案1】:

    您需要将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]
    ...
    

    有关 python3 中的字符串和字节的更多信息,请参阅this SO question

    【讨论】:

    • 谢谢!我认为这(或其他什么?)可能会导致另一个错误。 “TypeError:ord() 预期的长度为 1 的字符串,但找到了 int”我相信 ord() 应该返回一个表示输入字符串的 Unicode 代码点的整数......你可以在这段代码中具体指导我什么?
    • 完美运行!已经为此苦苦挣扎了几个小时,谢谢!我无法弄清楚它背后的逻辑。
    猜你喜欢
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 2019-01-16
    • 2019-02-13
    相关资源
    最近更新 更多