python-3.x - 如何解决不能在类似字节的对象上使用字符串模式
问题描述
在我升级到 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 个字节的缓冲区
我该如何解决这个问题。
解决方案
我通过使用 decode 函数将 manual_resync_time 转换为字符串和秒数来解决上面的问题
推荐阅读
- mysql - SQL Query 连接表并返回所有具有动态 id 的记录
- javascript - 如何从 world.js 访问函数?
- java - 尝试使用自定义 ClassLoader 从 ByteArray 加载 jar 时引发 FactoryConfigurationError
- sql - 如何在嵌套查询中排序?
- delphi - 带有长文本的 Delphi TLabel
- perl - “Perl 的 if 语句过滤器”
- javascript - 如何用这个数组做一个循环?
- graphql - AWS Appsync - 对从列表查询返回的行设置限制
- gatsby - 如何创建用于 activeClassName 的 CSS 类
- python - Google Drive API 从字符串上传文件