如何强制setup.py包含`\uuuu init\uuuu.py`文件并使我的包可导入?

2024-06-01 08:01:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让使用pip安装Python的人能够导入我的Pythonproject。尽管它包含一个__init__.py并在本地作为一个包工作,但我似乎误解了setuptools的工作原理

我运行以下三个命令来上传包

python3 setup.py sdist bdist_wheel
python3 -m pip install  --upgrade twine
python3 -m twine upload dist/*

然后在另一台机器上运行pip3 install smux.py。结果是,我可以作为命令访问smux.py,但在尝试导入时出现导入错误

python3
Python 3.8.5 (default, Jul 28 2020, 12:59:40) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import smux
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'smux'

运行上面的setup.py命令后,我检查了当前目录中的smux.py.egg-info/SOURCES.txt,发现它包含以下内容:

README.md
setup.py
smux.py
smux.py.egg-info/PKG-INFO
smux.py.egg-info/SOURCES.txt
smux.py.egg-info/dependency_links.txt
smux.py.egg-info/top_level.txt

缺少文件__init__.py

如何将该文件放入包中,或修改设置调用以使smux可导入?


Tags: installpip文件py命令infotxtinit
2条回答

另一个答案是更为洁净和现代的答案,如果我没有依赖于名称smux.py的遗留脚本,我会使用它并将脚本命名为smux。不幸的是,其他人已经包装了smux.py,破坏他们的脚本是不友好的

下面是我为避免循环依赖性问题所做的工作,循环依赖性问题是由于遗留脚本名以.py结尾并与模块命名冲突而产生的

最后,我修改了setup调用,使其具有以下两种功能

  py_modules=['smux'],
  scripts=['smux.py']

我的实验表明,这具有使模块可导入的预期效果,同时保留名为smux.py的工作脚本

您的setup调用如下所示:

setup(
  name="smux.py",
  version='0.1.1',
  scripts=['smux.py'],
  author="Henry Qin",
  author_email="root@hq6.me",
  description="Simple tmux launcher that will take less than 2 minutes to learn and should work across all versions of tmux",
  long_description=long_description,
  platforms=["All platforms that tmux runs on."],
  license="MIT",
  url="https://github.com/hq6/smux"
)

使用scripts参数,您已经告诉setuptools smux.py是一个脚本,而不是一个模块。因此,它将作为脚本而不是模块安装

您的代码不需要__init__.py,也不应该有一个。拥有一个__init__.py是没有帮助的。您需要告诉setuptools以模块而不是脚本的形式安装文件,并使用entry_points参数中的^{}项单独注册入口点:

setup(
    ...
    # no scripts= line
    py_modules=['smux'],
    entry_points={
        'console_scripts': ['smux=smux:main']
    }
)

然后,在安装代码时,smux将是可导入的,并且可以从调用smux.main的命令行获得一个smux脚本

相关问题 更多 >