0

After I upgraded to python 3 am getting error cannot use a string pattern on a bytes-like object.

Below is my code, am getting error on the 2nd line as there is string and byte mismatch.

 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)

I have tried using struct unpack to convert manually_resync_time to float

struct.unpack('f', manually_resync_time) 

and now its giving me

struct.error: unpack requires a buffer of 4 bytes

How can I resolve this.

Coder
  • 107
  • 4
  • 15
  • 1
    Have you tried just converting `manually_resync_time` to a `str` by using `.decode()` on it? – Green Cloak Guy Sep 07 '20 at 03:08
  • @GreenCloakGuy yeah I tried that before and it gave me TypeError: '<' not supported between instances of 'float' and 'str' for line #3 – Coder Sep 07 '20 at 03:13
  • 1
    `float(seconds)`? Were you trying to compare `0.01` with the string you got from the regex, `'32.53'` or whatever? – Green Cloak Guy Sep 07 '20 at 03:17
  • Does this answer your question? [Convert bytes to a string](https://stackoverflow.com/questions/606191/convert-bytes-to-a-string) and [How do I parse a string to a float or int?](https://stackoverflow.com/q/379906/4518341) – wjandrea Sep 07 '20 at 03:21
  • @GreenCloakGuy Currently yes, and it worked on py2 but I think instead of converting it to string I'll need a way to have both variables in float type and then the comparison would work, and that why I tried struct. – Coder Sep 07 '20 at 03:22
  • Oh, wait a minute, why are you expecting this to work at all? `manually_resync_time` doesn't contain any periods or the word "seconds". – wjandrea Sep 07 '20 at 03:24
  • @wjandrea Sorry, I have updated the question with the correct value – Coder Sep 07 '20 at 03:32

1 Answers1

0

I resolved above by converting manually_resync_time to string using decode function and the seconds to float

Coder
  • 107
  • 4
  • 15