Python 创建 pip 包 - 找不到模块



我正在尝试创建一个python包来分发我的代码。我在创建包和安装创建的包时没有收到任何错误。

但是,安装后,当我尝试导入软件包时,我收到错误ModuleNotFoundError:

以下是代码

hello_world.py

class HelloWorld:
def print_msg(self):
print("Hello World")

setup.py

from setuptools import setup, find_packages
setup(
name = "HelloWorld",
version = "0.1",
packages = find_packages(),
)

创建包

▶ python setup.py bdist_wheel
running bdist_wheel
running build
installing to build/bdist.macosx-10.14-x86_64/wheel
running install
running install_egg_info
running egg_info
writing HelloWorld.egg-info/PKG-INFO
writing dependency_links to HelloWorld.egg-info/dependency_links.txt
writing top-level names to HelloWorld.egg-info/top_level.txt
reading manifest file 'HelloWorld.egg-info/SOURCES.txt'
writing manifest file 'HelloWorld.egg-info/SOURCES.txt'
Copying HelloWorld.egg-info to build/bdist.macosx-10.14-x86_64/wheel/HelloWorld-0.1-py3.7.egg-info
running install_scripts
creating build/bdist.macosx-10.14-x86_64/wheel/HelloWorld-0.1.dist-info/WHEEL
creating 'dist/HelloWorld-0.1-py3-none-any.whl' and adding 'build/bdist.macosx-10.14-x86_64/wheel' to it
adding 'HelloWorld-0.1.dist-info/METADATA'
adding 'HelloWorld-0.1.dist-info/WHEEL'
adding 'HelloWorld-0.1.dist-info/top_level.txt'
adding 'HelloWorld-0.1.dist-info/RECORD'
removing build/bdist.macosx-10.14-x86_64/wheel

安装软件包

~/PycharmProjects/test_dist ▶ pip install dist/HelloWorld-0.1-py3-none-any.whl
Processing ./dist/HelloWorld-0.1-py3-none-any.whl
Installing collected packages: HelloWorld
Successfully installed HelloWorld-0.1
~/PycharmProjects/test_dist ▶ pip freeze
HelloWorld==0.1

导入模块时出错

>>> import HelloWorld
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'HelloWorld'

hello_world.py在哪里?它是否在setup.py旁边的根文件夹中?还是在某个子目录中?我怀疑是前者。这意味着你没有任何包,所以find_packages()返回一个空列表,所以setuptools不要;t 将任何代码打包到包中。

您的hello_world.py不是包(带有文件__init__.py的目录(,它是一个独立的模块,此类模块必须使用py_modules打包。这是你应该如何写你的setup.py

from setuptools import setup
setup(
name = "HelloWorld",
version = "0.1",
py_modules = ['hello_world'],
)

相关内容

  • 没有找到相关文章

最新更新