Pydev 2.5和Python 3.2中存在一个问题,试图将模块内容“加载”到交互式控制台中:当你按Ctrl + Alt + Enter时,Pydev会激活execfile(filename)而不是exec(编译(打开(文件名) ).read(),filename,'exec'),globals,locals) - 后者是execfile()在Python 3 +中的替代......
那么,如何改变这种行为?
ETA:更具体一点,事情是这样的:我创建一个新的PyDev模块,说'test.py',写一些简单的函数def f(n):print(n),按Ctrl + Alt +输入,然后我选择“当前活动编辑器的控制台”和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 :(得分:0)
编辑:
实际问题是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 ,它应该可以正常工作 - 如果没有,请告诉我。)
初步答复:
这是不可能的,但是当你在Python 3的控制台上时,PyDev确实重新定义了execfile,所以,它应该仍然可以工作......是不是因为某种原因不适合你?
此外,对于Python 3中的某些情况,替换:exec(compile(open(filename).read(),filename,'exec'),globals,locals)已被破坏。
实际的重新定义(应该适用于所有情况并且在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