Better Regex and exception handling for this small code
Ganesh Pal
ganesh1pal at gmail.com
Tue Jul 11 12:33:04 EDT 2017
I am trying to open a file and check if the pattern i.e initiator_crc has
changed after the task got completed? *
On Tue, Jul 11, 2017 at 10:01 PM, Ganesh Pal <ganesh1pal at gmail.com> wrote:
> Dear Python friends
>
> I am trying to open a file and check if there is a pattern has changed
> after the task got completed?
>
> file data:
> ........................................................
>
> #tail -f /file.txt
> ..........................................
> Note: CRC:algo = 2, split_crc = 1, unused = 0, initiator_crc = b6b20a65,
> journal_crc = d2097b00
> Note: Task completed successfully.
> Note: CRC:algo = 2, split_crc = 1, unused = 0, initiator_crc = d976d35e,
> journal_crc = a176af10
>
>
> I have the below piece of code but would like to make this better more
> pythonic , I found regex pattern and exception handling poor here , any
> quick suggestion in your spare time is welcome.
>
>
> #open the existing file if the flag is set and check if there is a match
>
> log_file='/file.txt'
> flag_is_on=1
>
> data = None
> with open(log_file, 'r') as f:
> data = f.readlines()
>
>
> if flag_is_on:
> logdata = '\n'.join(data)
> reg = "initiator_crc =(?P<ini_crc>[\s\S]*?), journal_crc"
> crc = re.findall(re.compile(reg), logdata)
> if not crc:
> raise Exception("Pattern not found in logfile")
>
> checksumbefore = crc[0].strip()
> checksumafter = crc[1].strip()
> logging.info("checksumbefore :%s and checksumafter:%s"
> % (checksumbefore, checksumafter))
>
> if checksumbefore == checksumafter:
> raise Exception("checksum not macthing")
>
> I am on Linux and Python 2.7
>
> Regards,
> Ganesh
>
>
More information about the Python-list
mailing list