简体   繁体   中英

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

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      

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, eg UTF-8:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM