nallapayan 420
nallapayan 420

Reputation: 1

Regular expression is not working in python script

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')

Upvotes: 0

Views: 237

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545923

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')
    

Upvotes: 0

Ashish Karn
Ashish Karn

Reputation: 1143

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      

Upvotes: 1

Related Questions