我正在将项目打包到wheel文件中,但无法获得正确的导入路径。
项目很简单:
.
├── setup.py
└── src
├── europe
│ ├── germany.py
│ └── __init__.py
├── hello.py
└── __init__.py
# setup.py:
from setuptools import setup
from setuptools import find_packages
setup(
name="hello_world",
version="1.0.0",
description='testing setuptools',
packages=find_packages(where="."),
zip_safe=False,
python_requires='>=3.0',
install_requires=[],
entry_points={
"console_scripts": ["hello_world = src.hello:main"]
},
)
# src/__init__.py
from . import europe
# src/hello.py
from src.europe.germany import hello_germany
def main():
hello_germany()
if __name__ == '__main__':
main()
src/europe/__init__.py
什么都没有
# src/europe/germany.py
def hello_germany():
print("gutten Tag")
使用当前代码,我可以打包并安装(这一步需要
setuptools
和 wheel
,两者都可以从 conda 或 pip 安装),然后我得到了一个可执行二进制文件 hello_world
:
$ python3 setup.py install
$ hello_world
gutten Tag
工作正常,没有任何问题。
但我无法再将它作为 python 脚本调用:
$ pip uninstall hello-world
$ python3 src/hello.py
Traceback (most recent call last):
File "blahblah/src/hello.py", line 1, in <module>
from src.europe.germany import hello_germany
ModuleNotFoundError: No module named 'src'
它抱怨导入声明
from src.europe.germany import hello_germany
无法找到src
。
我当然可以将
from src.europe.germany import hello_germany
更改为from europe.germany import hello_germany
,但这样打包和安装就不再起作用了:
$ python3 setup.py install
$ hello_world
File "blahblah/anaconda3/envs/py312/lib/python3.12/site-packages/hello_world-1.0.0-py3.12.egg/src/hello.py", line 1, in <module>
from europe.germany import hello_germany
ModuleNotFoundError: No module named 'europe'
它抱怨模块
europe
找不到。
如何修复此代码以使其既作为脚本又作为 pip 轮包运行?
如果您已在本地安装了软件包,则可以使用软件包名称导入模块:
from hello_world.europe.germany import hello_germany
如果未安装该软件包,则需要更新 python 路径,以便它同时具有父目录和同级目录。
import sys
import os
sys.path.append(os.path.abspath('..'))
sys.path.append(os.path.abspath('../src'))
from src.europe.germany import hello_germany