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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.