2016-09-20 112 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()