我正在使用setuptools和pkg_resources处理包P,
在安装之后,软件包需要下载一些二进制文件并将它们放在专用目录(P / bin /)中.
我正在尝试使用pkg_ressources.resource_filename来获取绝对目录路径. (为了与virtualenv合作)
在使用python setup.py install进行安装期间,pkg_ressources.resource_filename不会返回
像/home/user/tests/venv/lib/python3.4/site-package/P/bin/这样的路径,但是实际模块的路径,比如/ home / user / projects / P / P / bin /.
这是一个问题,因为我需要安装目录(在virtualenv内),而不是我的个人项目目录(我开发模块).
如果我尝试使用pip install模块传递pypi,pkg_ressources.resource_filename返回的目录是一个临时文件,如/ tmp / pip-build-xxxxxxx / P / bin /,这也不是二进制文件所在的位置放.
这是我的setup.py:
from setuptools import setup
import os
from setuptools.command.install import install as _install
from pkg_resources import resource_filename
def post_install():
"""Get the binaries online, and give them the execution permission"""
package_dir_bin = resource_filename('P', 'bin') # should be /home/user/tests/venv/lib/python3.4/site-package/P/bin/
# package_dir_bin = resource_filename(Requirement.parse('P'), 'bin') # leads to same results
put_binaries_in(package_dir_bin)
os.system('chmod +x ' + package_dir_bin + '*')
class install(_install):
# see https://stackoverflow.com/a/18159969
def run(self):
"""Call superclass run method, then downloads the binaries"""
_install.run(self)
self.execute(post_install, args=[], msg=post_install.__doc__)
setup(
cmdclass={'install': install},
name = 'P',
# many metadata
package_dir = { 'P' : 'P'},
package_data = {
'P' : ['bin/*.txt'] # there is an empty txt file in bin directory
},
)
在安装,跨平台和兼容的python 2和3期间是否有标准方法来获取安装目录?
如果没有,我该怎么办?
最佳答案 解决方法是使用站点包而不是pkg_resources,它们似乎不是为安装期间的访问资源而设计的.
这是一个在安装过程中检测安装目录的函数:
import os, sys, site
def binaries_directory():
"""Return the installation directory, or None"""
if '--user' in sys.argv:
paths = (site.getusersitepackages(),)
else:
py_version = '%s.%s' % (sys.version_info[0], sys.version_info[1])
paths = (s % (py_version) for s in (
sys.prefix + '/lib/python%s/dist-packages/',
sys.prefix + '/lib/python%s/site-packages/',
sys.prefix + '/local/lib/python%s/dist-packages/',
sys.prefix + '/local/lib/python%s/site-packages/',
'/Library/Python/%s/site-packages/',
))
for path in paths:
if os.path.exists(path):
return path
print('no installation path found', file=sys.stderr)
return None
在使用virtualenv进行安装的情况下,此解决方案不兼容Python 2.7,因为有关模块站点的known bug. (见相关SO)