re-initializing PLY parser

586 views Asked by At

I wrote a parser using PLY and it does what I need. Now, I would like to parse multiple files using the parser class. Instead of instantiating the parser class for each file, I would like to re-use the same instantiated class for all files (so that I can accumulate some results in the parser class).

Parsing of one file may not complete nicely so that I would like to re-initialize the parser before feeding another file.

What is the correct way to re-initialize a PLY parser? (Or, I shouldn't reuse a parser?)

1

There are 1 answers

0
this be Shiva On

If you want to reuse the same parser for multiple files, but reset the stack each time, you can use the restart function:

parser = yacc.yacc()
for file in file_list:
    with open(file) as fp:
       parser.parse(fp.read())
       ... # accumulate logging info
       parser.restart() # this discards the entire parsing stack and resets the parser to its initial state

More can be found at the official documentation.