2012-04-13 106 views
1

Pydev 2.5和Python 3.2中存在一個問題,試圖將模塊內容「加載」到交互式控制檯中:當您按Ctrl + Alt + Enter時,Pydev會啓動execfile(文件名)而不是exec(compile(open(filename) .read(),filename,'e​​xec'),globals,locals) - 後者是execfile()在Python 3+中的替換... ...如何使用exec()在Pydev上替換execfile()Ctrl + Alt + Enter鍵綁定?

那麼,如何改變這種行爲呢?我想創建一個新的PyDev模塊,比如'test.py',寫一些簡單的函數def f(n):print(n),按Ctrl + Alt + Enter鍵,然後我選擇「控制檯當前活動的編輯器」和Python 3.2解釋器,交互式控制檯醒來,然後我得到這個:

>>> import sys; print('%s %s' % (sys.executable or sys.platform, sys.version)) 
PyDev console: using default backend (IPython not available). 
C:\Program Files (x86)\Python\3.2\python.exe 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] 

>>> execfile('C:\\testy.py') 
>>> f(1) 
Traceback (most recent call last): 
    File "<console>", line 1, in <module> 
NameError: name 'f' is not defined 

正如你所看到的,它仍然使用的execfile()代替EXEC(),它取代了它在Python 3 + ...

回答

0

編輯:

實際proble m是execfile在PyDev重定義中沒有得到適當的全局變量。所以,如果execfile執行了execfile('my_file',globals()),它會工作...我將更改PyDev的實現,以便如果全局變量不通過,它將執行:

if glob is None: 
    import sys 
    glob = sys._getframe().f_back.f_globals 

(你可以修復你的本地安裝plugins/org.python.pydev_XXX/PySrc/_pydev_execfile.py它應該可以工作 - 請讓我知道如果它不)。


最初的回答:

那是不可能的,但確實的PyDev當你在其上的Python 3控制檯是重新定義的execfile,所以,它應該仍然工作...是不是爲你工作的一些原因?

此外,換貨:EXEC(編譯(開放(文件名).read(),文件名, 'EXEC'),全局,當地人)被打破了在Python 3

實際重定義(某些情況下,這應該適用於所有情況,並提供在PyDev的)是:

#We must redefine it in Py3k if it's not already there 
def execfile(file, glob=None, loc=None): 
    if glob is None: 
     glob = globals() 
    if loc is None: 
     loc = glob 
    stream = open(file, 'rb') 
    try: 
     encoding = None 
     #Get encoding! 
     for _i in range(2): 
      line = stream.readline() #Should not raise an exception even if there are no more contents 
      #Must be a comment line 
      if line.strip().startswith(b'#'): 
       #Don't import re if there's no chance that there's an encoding in the line 
       if b'coding' in line: 
        import re 
        p = re.search(br"coding[:=]\s*([-\w.]+)", line) 
        if p: 
         try: 
          encoding = p.group(1).decode('ascii') 
          break 
         except: 
          encoding = None 
    finally: 
     stream.close() 

    if encoding: 
     stream = open(file, encoding=encoding) 
    else: 
     stream = open(file) 
    try: 
     contents = stream.read() 
    finally: 
     stream.close() 

    exec(compile(contents+"\n", file, 'exec'), glob, loc) #execute the script 
+0

我真的不知道,如果我理解,所以我說,導致這一問題的具體步驟,現在我想弄清楚我應該如何使用這個重新定義你發佈的修復這個惱人的小錯誤(如果確實是一個錯誤)... – Rok 2012-04-14 22:25:23

+0

好吧,只是看到那裏的錯誤......它沒有得到正確的全局()。將修復答案以反映這一點。 – 2012-04-16 00:02:55

+0

它的工作原理! :) 路徑中只有一個小錯誤 - 它應該是: plugins \ org.python.pydev_XXX \ PySrc \ _pydev_execfile.py (最後一個反斜槓丟失) – Rok 2012-04-16 14:48:09