Intercepting python interpreter code before it executes
<p>Is it possible to intercept interpreter's code before it executes?</p>

<p>Let's say I want to handle a case like:</p>

<pre><code>&gt;&gt;&gt; for f in glob.glob('*.*'): # I'd like to intercept this code before it executes 
...     something_to_do(f)     # and play with it in some dangerous fashion :)
...
ERROR: Using glob not allowed. # e.g.
</code></pre>

<p>But there are tons of other examples (like altering the code, or sending it somewhere).</p>

<p>I can write my own interpreter, but that's not really the point.</p>

<p>Ok, solved it by creating new module which starts new interpreter instance and do whatever.</p>

<p>I just put the code below in the module and import it.</p>

<pre><code>import code

class GlobeFilterConsole(code.InteractiveConsole):
    def push(self, line):
        self.buffer.append(line)
        source = "\n".join(self.buffer)

        if 'glob' in source: # do whatever you want with the source
            print('glob usage not allowed')
            more = False
        else:
            more = self.runsource(source, self.filename)

        if not more:
            self.resetbuffer()
        return more


console = GlobeFilterConsole()
console.interact()
</code></pre>

python interpreter