想象一下这个项目结构:
myproject
|-- mypkg1
| |-- __init__.py
| |-- __main__.py
| |-- mod1.py
| |-- mod2.py
| |-- standalone.py
|
|-- mypkg2
| |-- __init__.py
| |-- mod1.py
| |-- mod2.py
|
|-- tests
| |-- mypkg1
| | | --mod1_test.py
| |-- mypkg1_mod1_test.py
|
|-- mypkg1_run.py
|-- standalone_run.py
|-- conftest.py
|-- README
具有以下文件内容:
mypkg1 .__ init __。py
import sys
import inspect
from pathlib import Path
sys.path.append(str((Path(inspect.getfile(inspect.currentframe())) / '../..').resolve()))
mypkg1 .__ main __。py
from .mod1 import mod1_msg
from .mod2 import mod2_msg
from mypkg2 import mod1, mod2
def main():
print("Hello from mypkg1 main!")
print(mod1_msg())
print(mod2_msg())
print(mod1.mod1_msg())
print(mod2.mod2_msg())
if __name__ == '__main__':
main()
mypkg1.mod1.py
def mod1_msg():
return "Hello from mypkg1.mod1!"
mypkg1.mod2.py
from .mod1 import mod1_msg
def mod2_msg():
return "Hello from mypkg1.mod2 and {}".format(mod1_msg())
mypkg1.standalone.py
from .mod2 import mod2_msg
def main():
print("Hello from mypkg1.standalone!")
print(mod2_msg())
if __name__ == '__main__':
main()
mypkg2 .__ init __。py
import sys
import inspect
from pathlib import Path
sys.path.append(str((Path(inspect.getfile(inspect.currentframe())) / '../..').resolve()))
mypkg2.mod1.py
def mod1_msg():
return "Hello from mypkg2.mod1!"
mypkg2.mod2.py
from .mod1 import mod1_msg
def mod2_msg():
return "Hello from mypkg2.mod2 and {}".format(mod1_msg())
tests.mypkg1.mod1_test.py 和 tests.mypkg1_mod1_test.py
from mypkg1.mod1 import mod1_msg
def test_mod1():
assert mod1_msg() == "Hello from mypkg1.mod1!"
mypkg1_run.py
from mypkg1.__main__ import main
if __name__ == '__main__':
main()
standalone_run.py
from mypkg1.standalone import main
if __name__ == '__main__':
main()
常规存储库要求
必需的使用行为
必需的测试行为
结论
sys.path.append(str((Path(inspect.getfile(inspect.currentframe())) / '../..').resolve()))
最后是我的问题
ModuleNotFoundError: No module named '__main__.mod2'; '__main__' is not a package
此错误是由程序包中的相对导入引起的。