【问题标题】:Python Packaging with .pth files带有 .pth 文件的 Python 打包
【发布时间】:2018-06-25 22:51:52
【问题描述】:

我有一套包,它们一起开发并捆绑到一个分发包中。

为了争论,假设我有充分的理由按以下方式组织我的 python 分发包:

SpanishInqProject/
|---SpanishInq/
|     |- weapons/
|     |   |- __init__.py
|     |   |- fear.py
|     |   |- surprise.py    
|     |- expectations/
|     |   |- __init__.py
|     |   |- noone.py
|     |- characters/
|         |- __init__.py
|         |- biggles.py
|         |- cardinal.py
|- tests/
|- setup.py
|- spanish_inq.pth

我已经添加了路径配置文件spanish_inq.pthSpanishInq添加到sys.path,所以我可以直接导入weapons,.etc。

我希望能够使用 setuptools 来构建轮子并在 SpanishInq 目录中安装 pip weaponsexpectationscharacters,但 没有 使 SpanishInq 成为包或命名空间。

我的 setup.py:

  from setuptools import setup, find_packages

  setup(
    name='spanish_inq',
    packages=find_packages(),
    include_package_data=True,       
   )

MANIFEST.in 文件包含:

   spanish_inq.pth

这在几个方面具有挑战性:

  • pip install 已将weapons 等直接放在site-packages 目录中,而不是放在SpanishInq 目录中。
  • 我的spanish_inq.pth 文件最终位于 sys.exec_prefix 目录中,而不是在我的 site-packages 目录中,这意味着其中的相对路径现在没有用了。

我能够通过将 SpanishInq 转换为模块来解决的第一个问题(我对此并不满意),但我仍然希望能够在没有将 SpanishInq 作为命名空间的情况下导入 weapons 等,并且为此,我需要将 SpanishInq 添加到 sys.path,这是我希望 .pth 文件能提供帮助的地方......但我无法让它去它应该去的地方。

所以...

如何将.pth 文件安装到site-packages 目录中?

【问题讨论】:

  • 您希望能够编写import weapons for weapons/ 在安装时存储在SpanishInq 目录中?为什么? SpanishInq 有什么可能的用途?
  • 仅仅作为一个容器。让我们假设在 SpanishInq 中可能有几十个包,而不是把站点包弄得乱七八糟,我们希望它们很好地组合在一起,因为无论如何它们都作为一个包安装。为了让事情更有趣,假设我们有几个项目(每个项目都在不同的环境中工作),每个项目可能会分叉 SpanishInqProject,每个分叉可能包含不同数量的包。假设我有一些需要处理的限制。我有充分的理由。
  • ...虽然我很想听听以这种方式对包进行分组的缺点或注意事项。

标签: python python-2.7 setuptools python-packaging pth


【解决方案1】:

这与setup.py: installing just a pth file? 非常相似(就功能而言,这个问题严格来说是一个超集)——我已经在下面调整了我的答案的相关部分。


这里正确的做法是扩展 setuptools 的build_py,并将 pth 文件复制到 build 目录中,在 setuptools 准备所有进入站点包的文件的位置。

from setuptools.commands import build_py


class build_py_with_pth_file(build_py):
     """Include the .pth file for this project, in the generated wheel."""

     def run(self):
         super().run()

         destination_in_wheel = "spanish_inq.pth"
         location_in_source_tree = "spanish_inq.pth"
 
         outfile = os.path.join(self.build_lib, destination_in_wheel)
         self.copy_file(location_in_source_tree, outfile, preserve_mode=0)

setup(
   ...,
   cmdclass={"build_py": build_py_with_pth_file},
)

【讨论】:

    猜你喜欢
    • 2010-11-25
    • 2017-09-11
    • 2014-10-31
    • 2013-02-18
    • 1970-01-01
    • 2018-07-19
    • 2013-11-23
    • 1970-01-01
    • 2018-12-26
    相关资源
    最近更新 更多