2014-05-08 58 views
2

我有一個python包,需要通過pip作爲我的項目需求文件的一部分進行安裝,但我需要將一些文件從我的包複製到項目中安裝這個軟件包。我在想setup()使用data_files選項做的一樣:setup.py,pip - 獲取python包的執行源路徑

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

,我woud喜歡將這些文件複製到相關的地方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不應該這樣使用,但我真的需要打包一些文件在可安裝的軟件包中,並在安裝時將它們複製/移動到項目根目錄。

有關如何完成此任務的任何建議?

謝謝! :)

+0

您是否創建了該軟件包,還是您下載並正在修改的軟件包?其次,你希望用這個解決什麼問題,因爲這絕對不是正確的方法。 –

+0

我創建了它。我正在嘗試構建某種類型的django-app「kickstarter」,它將包含一些可重複使用的實用程序作爲django應用程序供以後使用,並且我需要複製一些文件作爲此「kickstart」過程的一部分。我知道這不是最好的方式。只要這個過程可以在我使用pip安裝我的軟件包的時候觸發,我就會接受任何建議。 – Gerard

+0

我會推薦[cookiecutter](https://github.com/audreyr/cookiecutter)更適合這個。 –

回答

1

與其試圖強制setuptools執行引導操作,不如考慮像cookiecutter這樣的工具,這些工具旨在處理各種項目的其他引導和設置任務。

還有一些可用於django的模板(例如,參見here)。

1

使用pkg_resources

這個包被安裝了setuptools的。

從包文檔字符串:

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安裝)等命令經常使用這個模式。