Reuse lexer object in antlr4 python target
<p>I have a simple antlr4 lexer, the following script works,</p>

<pre><code>    lexer  = MyLexer(InputStream(argv[1]))
    stream = CommonTokenStream(lexer)
    parser = MyParser(stream)
    tree   = parser.query()

    v = MyVisitor()
    v.visit(tree)
</code></pre>

<p>But I'm wondering if I can reuse the <code>MyLexer</code> class object?</p>

<p>If so, how can I re-set the input string? </p>

<p>It's possible by setting an input stream in the lexer (could even be the same as before) via <code>lexer.setInputStream()</code>. Then also re-set the lexer in the parser (can also be the same) via <code>parser.setTokenSource()</code>. Finally call <code>stream.reset()</code> and <code>parser.reset()</code> if you re-use them too.</p>

<p>FYI: if you even want to re-use the input stream you can call <code>input.load(text)</code> on it to load the new input.</p>

python antlr antlr4