首页 > 解决方案 > 如何解决不能在类似字节的对象上使用字符串模式

问题描述

在我升级到 python 3 后,我得到错误 cannot use a string pattern on a bytes-like object。

下面是我的代码,由于字符串和字节不匹配,第二行出现错误。

 manually_resync_time =  b'2020-09-07T03:28:55Z chronyd version 3.5 starting (+CMDMON +NTP +REFCLOCK +RTC +PRIVDROP +SCFILTER +SIGND +ASYNCDNS +SECHASH +IPV6 +DEBUG)\n2020-09-07T03:28:55Z Could not open IPv6 command socket : Address family not supported by protocol\n2020-09-07T03:28:55Z Frequency -9.450 +/- 0.094 ppm read from /var/lib/chrony/drift\n2020-09-07T03:29:28Z System clock wrong by 0.000071 seconds (step)\n2020-09-07T03:29:28Z chronyd exiting\n'

 seconds = re.search( "([0-9]*.[0-9]*) seconds", manually_resync_time).group(0)
 self.assertLess(0.01, seconds)

我尝试使用 struct unpack 将 manual_resync_time 转换为 float

struct.unpack('f', manually_resync_time) 

现在它给了我

struct.error: unpack 需要 4 个字节的缓冲区

我该如何解决这个问题。

标签: python-3.x

解决方案


我通过使用 decode 函数将 manual_resync_time 转换为字符串和秒数来解决上面的问题


推荐阅读