12

python docsによると、相対インポートとパッケージ内参照は python 2.5 以降でサポートされています。現在、Python 2.7.3 を実行しています。そこで、より簡単にインポートできるように、これを自分のパッケージに実装しようとしました。SyntaxError 例外がスローされたことに驚き、誰かがその原因を突き止める手助けをしてくれることを期待していました。

テスト用のテスト ディレクトリをセットアップします。

tester
├── __init__.py
├── first_level.py
└── sub
    ├── __init__.py
    └── second_level.py

両方の __init__.py モジュールが空です。他のモジュールは次のとおりです。


# first_level.py
print "This is the first level of the package"

# sub/second_level.py
import ..first_level
print "This is the second level"

second_level モジュールをインポートしようとすると、次のエラーが発生します。

Python 2.7.3 (default, Aug  1 2012, 14:42:42) 
[GCC 4.2.1 Compatible Apple Clang 4.0 ((tags/Apple/clang-421.0.57))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Welcome!
>>> import tester
>>> import tester.sub.second_level
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "tester/sub/second_level.py", line 1
    import ..first_level
           ^
SyntaxError: invalid syntax

2 行が次々に出力されると思っていましたが、代わりに例外が発生します。それで、私はインポートを間違っていますか?他にアイデアはありますか。

4

2 に答える 2

16

そのようなモジュールをインポートすることはできません。 import ..blahは有効なインポート構文ではありません。あなたがする必要がありますfrom .. import first_level

于 2012-09-13T02:10:45.440 に答える
-2

私は通常、次のようなことをします:

import sys 
sys.path.append("/home/me/tester")
import first_level 

お役に立てれば。〜ベン

于 2012-09-13T02:11:10.503 に答える