1

I need to parse the following three lines:

Uptime is 1w2d
Last reset at 23:05:56
  Reason: reload

But last two lines are not always there, output could look like this prior to 1st reboot:

Uptime is 1w2d
Last reset

My parser looks like this:

parser = SkipTo(Literal('is'), include=True)('uptime') +
         delimitedList(Suppress(SkipTo(Literal('at'), include=True))'(reset)' +
             SkipTo(Literal(':'), include=true) +
             SkipTo(lineEnd)('reason'), combine=True)
         )

It works in first case with 3 lines, but doesnt work with second case.

1 Answer 1

2

I will use for the file that you've reported this syntax (supposing that the order is relevant):

from pyparsing import Literal, Word, alphanums, nums, alphas, Optional, delimitedList

def createParser():
    firstLine = Literal('Uptime is') + Word(alphanums)
    secLine = Literal('Last reset at') + delimitedList(Word(nums) + Literal(':') + Word(nums) + Literal(':') + Word(nums))
    thirdLine = Literal('Reason:') + Word(alphas)

    return firstLine + secLine + Optional(thirdLine)

if __name__ == '__main__':
     parser = createParser()
     firstText = """Uptime is 1w2d\n
     Last reset at 23:05:56\n
     Reason: reload"""

     print(parser.parseString(firstText))

Declaring a parsing element optional you are able to let the parser skip it when it is not present, without raising any errors.

Sign up to request clarification or add additional context in comments.

4 Comments

+1, nice answer, Optional is definitely the way to go in solving this issue. I'm guessing that "Reason:" could reflect anything typed in by someone restarting the system, and could be more than one word in length. I would go with Literal("Reason:") + restOfLine instead, which will take in everything up to the next newline or the end of the input string if there are no more newlines.
!Allessandro looks good, I will test it. Thanks Paul, restOfLine is a nice one
If you think that it's a good code, consider to mark my comment as an answer. Thank you
Solution works, I did line by line parsing and then construct a parser using Optional

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.