문제

How does one use absolute imports from a module of a sibling package?

Package file structure:

.
├── a
│   ├── __init__.py
│   └── modulea.py
├── b
│   ├── __init__.py
│   ├── moduleb.py
├── __init__.py
└── test.py

Files test.py and a/modulea.py:

from b.moduleb import f

if __name__ == '__main__':
    f()

File b/moduleb.py:

def f():
    print('hello')

This works:

% python test.py 
hello

This does not:

% python a/modulea.py 
Traceback (most recent call last):
  File "a/modulea.py", line 1, in <module>
    from b.moduleb import f
ImportError: No module named 'b'

As far as I can tell from the documentation it should work: http://docs.python.org/3.3/tutorial/modules.html#intra-package-references. Am I missing something?

도움이 되었습니까?

해결책

You need an __init__.py in whatever . is.

다른 팁

Use python -ma.modulea.

Running python a/modulea.py adds a directory to sys.path instead of the parent (.).

Don't run scripts from inside Python packages directly. See Traps for the Unwary.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top