0

the regular expression is not working. please find the below details.

cpu_pattern = re.compile('.*CPU.*(usr|user).*nice.*sys.*')

part = b'11:40:24 AM     CPU      %usr     %nice      %sys   %iowait    %steal      %irq     %soft    %guest     %idle\n11:40:25 AM     all      0.00      0.00      0.08      0.00      0.00      0.00      0.00      0.00     99.92'

IF condition:

if cpu_pattern.search(part): if cpu_usage == '': cpu_usage == part

Error:

TypeError('cannot use a string pattern on a bytes-like object')
8
  • As the error says, You 'cannot use a string pattern on a bytes-like object'. Your search-pattern is a string, the part variable is bytes. Commented Jul 17, 2020 at 8:29
  • how to resolve this issue Commented Jul 17, 2020 at 8:31
  • 1
    convert part to str Commented Jul 17, 2020 at 8:32
  • part is one of the list value Commented Jul 17, 2020 at 8:35
  • 1
    use: match = cpu_pattern.search(str(part)) Commented Jul 17, 2020 at 8:39

2 Answers 2

1

Please use below code to convert byte to string in python which will solve your issue:

part= part.decode("utf-8") 

Put above code after part obejct

Output print(part):

11:40:24 AM     CPU      %usr     %nice      %sys   %iowait    %steal      %irq     %soft    %guest     %idle                         
11:40:25 AM     all      0.00      0.00      0.08      0.00      0.00      0.00      0.00      0.00     99.92      
Sign up to request clarification or add additional context in comments.

Comments

0

part is not a string, it’s a byte sequence. You now have two choices; which is more appropriate depends on how part was generated:

  1. Perform byte-wise matching rather than string matching, by using a byte sequence pattern:

    cpu_pattern = re.compile(b'.*CPU.*(usr|user).*nice.*sys.*')
    
  2. Decode the parts byte sequence using an appropriate encoding, e.g. UTF-8:

    parts_str = parts.decode('utf-8')
    

1 Comment

**cpu_usage += "\n" + part ** Can only concatenate str (not "bytes") to str

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.