3

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

为了争论,假设我有充分的理由按以下方式组织我的 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.pth要添加SpanishInq到的路径配置文件sys.path,所以我可以直接导入weapons,.etc。

我希望能够使用 setuptools 构建轮子并在目录中安装 pip install ,但weapons无需创建或命名空间。expectationscharactersSpanishInqSpanishInq

我的 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 目录中,而不是在我的站点包目录中,这意味着其中的相对路径现在没用了。

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

所以...

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

4

1 回答 1

0

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


正确的做法是扩展 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},
)
于 2022-02-16T07:30:47.073 回答