1

Pydev 2.5 と Python 3.2 では、モジュールの内容を対話型コンソールに「」ロードしようとすると問題があります。Ctrl+Alt+Enter を押すと、Pydev は exec(compile(open(filename).read) ではなく execfile(filename) を起動します。 (), filename, 'exec'), globals, locals) - 後者は Python 3+ での execfile() の置き換えです.​​..

では、この動作を変更するにはどうすればよいでしょうか。

ETA: もう少し具体的に言うと、次のようになります: 新しい 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

ご覧のとおり、Python 3 以降では exec() の代わりに execfile() を使用しています...

4

1 に答える 1

0

編集:

実際の問題は、PyDev 再定義で execfile が適切なグローバルを取得していないことです。したがって、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(compile(open(filename).read(), filename, 'exec'), globals, locals) は、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
于 2012-04-14T16:34:48.713 に答える