setup.py,pip - 获取python包执行的原始路径

时间:2014-05-08 17:25:24

标签: python pip setuptools setup.py

我有一个python包需要通过pip安装,作为我项目的需求文件的一部分,但是我需要将我的包中的一些文件复制到安装此包的项目中。我正在考虑使用setup()中的data_files选项来执行此操作,例如:

setup(
    name='my_pacakge',
    ...
    data_files=[
        ('example/folder1', ['something1/file1.ext', 'something1/file2.ext']),
        ('folder2', ['something2/file1.ext', 'something2/file2.ext']),
    ]
)

我想把这些文件复制到相对于运行pip install my_package的目录的路径中,理想情况是我的项目根目录,留下如下的树

project_root
├── example
│   └── folder1
│       ├── file1.ext
│       └── file2.ext
└── folder2
    ├── file1.ext
    └── file2.ext

但为此我需要知道运行pip install my_package的绝对路径。我已尝试使用inspect.stackinspect.currentframesys.get_frameinspect.inspect.getouterframes(some_of_these_frames),但这只会向我提供有关安装时setup.py当前位置的信息,目录如

/private/var/folders/gq/vpylvs0d51162jtyqhtgdc6m0000gn/T/pip-tNcbvb-build
/var/folders/gq/vpylvs0d51162jtyqhtgdc6m0000gn/T/pip-6a8MKS-build/setup.py

对我来说根本没用。

现在,我知道setuptools / setup.py不应该像这样使用但我真的需要在可安装包中打包一些文件并将它们复制/移动到项目根目录安装时间。

有关如何完成此任务的任何建议?

谢谢! :)

2 个答案:

答案 0 :(得分:0)

使用pkg_resources

此软件包随setuptools一起安装。

来自包docstring:

Docstring:
Package resource API
--------------------

A resource is a logical file contained within a package, or a logical
subdirectory thereof.  The package resource API expects resource names
to have their path parts separated with ``/``, *not* whatever the local
path separator is.  Do not use os.path operations to manipulate resource
names being passed into the API.

The package resource API is designed to work with normal filesystem packages,
.egg files, and unpacked .egg files.  It can also work in a limited way with
.zip files and with custom PEP 302 loaders that support the ``get_data()``
method.

如果您使用zip_safe = False安装软件包,您的数据将在目录中提供。

使用zip_safe = True安装,它将成为鸡蛋的一部分。但是如果你需要使用那里的文件,这很容易,pkg_resources提供了很好的函数和方法

  • pkg_resources.resource_exists
  • pkg_resources.resource_isdir
  • pkg_resources.resource_stream - 提供类似文件的对象
  • pkg_resources.resource_filename
  • pkg_resources.resource_listdir
  • pkg_resources.resource_string

请注意,这甚至适用于zipsafe True安装。

只需将您的数据放入相对于包装目录的目录中即可。然后从你的代码:

import pkg_resources
fname = pkg_resources.resource_filename("your.package.name", "folder/example1.txt")

仅将其用于静态文件

不要试图让任何正在改变的文件。从技术上讲,它可能是(zip_safe = False文件就在那里),但它绝对是糟糕的设计(权限,包的更新)。

不要从pip初始化您的项目,更好地提供一些appinit命令

使用pip将数据安装到应用程序目录中是一种滥用行为。

我建议定义一个由我们的程序安装的命令,如appinit,并在需要填充目录时使用它。像buildout这样的命令(由zc.buildout安装)和其他命令经常使用这种模式。

答案 1 :(得分:0)

不要试图强制setuptools进行自举,而应考虑像cookiecutter这样的工具,这些工具旨在处理各种项目的其他引导和设置任务。

还有可用于django的模板(例如,请参阅here)。

相关问题