You need an __init__.py
in whatever .
is.
Import module from sibling package with absolute import
-
20-06-2023 - |
質問
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?
解決
他のヒント
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.
所属していません StackOverflow