2016-09-20 32 views
0

在执行它之前是否可以拦截解释器的代码?在执行之前拦截python解释器代码

比方说,我要处理这样的情况:

>>> 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. 

但也有吨的其他例子(如改变代码,或者某个地方将其发送)。

我可以写我自己的翻译,但那不是重点。

+0

你试图拦截使用'glob'模块,还是只是'glob'函数?该程序是否可以定义它自己的“glob”?也就是说,你只是想拦截一个特定的功能,或者拦截行为? – Dunes

+0

另外,你如何执行你想拦截的代码?例如。 'python somescript.py'或'exec(some_string)',或者...? – Dunes

+0

@Dunes你错过了这一点,“glob”并不重要。我觉得这将是很好,如果它会是某种功能,我会装饰和执行无论如何,所以我会失去任何功能。 – pprzemek

回答

0

好吧,通过创建新的模块来解决它,它启动新的解释器实例并执行任何操作。

我只是把下面的代码放在模块中并导入它。

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()