在安装期间复制配置文件的正确方法?

2024-09-29 06:31:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图分发我写的一个mplstyle,这样我就可以很容易地共享它了。它可以归结为在安装期间将文本文件复制到正确的配置方向(对于任何体系结构来说都是已知的)。我希望能够使用python setup.py installpip install ...安装。目前,我似乎没有得到这两种方法中的任何一种(参见下面的当前方法)。在

  • 使用pip install ...安装似乎根本不会调用复制。在
  • {my machine上安装{readme>会出现以下错误:

    python setup.py install --force
    
    running install
    error: [Errno 2] No such file or directory: u'/home/docs/.config/matplotlib/stylelib/goose.mplsty
    

在安装期间以可靠的方式复制配置文件的正确方法是什么?在

当前方法

文件结构

^{pr2}$

setup.py

from setuptools                 import setup
from setuptools.command.install import install

class PostInstallCommand(install):

  def run(self):

    import goosempl
    goosempl.copy_style()

    install.run(self)

setup(
  name              = 'goosempl',
  ...,
  install_requires  = ['matplotlib>=2.0.0'],
  packages          = ['goosempl'],
  cmdclass          = {'install': PostInstallCommand},
  package_data      = {'goosempl/stylelib':['goosempl/stylelib/goose.mplstyle']},
)

goosempl/__init__.py

def copy_style():

  import os
  import matplotlib

  from pkg_resources import resource_string

  files = [
    'stylelib/goose.mplstyle',
  ]

  for fname in files:
    path = os.path.join(matplotlib.get_configdir(),fname)
    text = resource_string(__name__,fname).decode()

    print(path, text)

    open(path,'w').write(text)

上载到PyPi

python setup.py bdist_wheel --universal
twine upload dist/*

Tags: installpippath方法textfrompyimport
1条回答
网友
1楼 · 发布于 2024-09-29 06:31:19

首先,根据您提供的项目结构,您没有正确地指定package_data。如果goosempl是一个包,并且stylelib是一个包含mplstyle文件的目录(我从您的代码中假设),那么您的package_data配置行应该是:

package_data = {'goosempl': ['stylelib/goose.mplstyle']},

Building and Distributing Packages with Setuptools所述:

The package_data argument is a dictionary that maps from package names to lists of glob patterns. The globs may include subdirectory names, if the data files are contained in a subdirectory of the package.

所以您的包是goosemplstylelib/goose.mplstyle是要包含在{}的包数据中的文件。在

您的第二个问题(No such file or directory)很简单:在copy_style()函数中,在写入文件之前,永远不会检查文件的父目录是否存在。您应该能够通过删除目录/home/<user>/.config/matplotlib/stylelib/(或临时移动它)在本地重新生成这个目录。在

修复也很简单,实际上有很多。使用任何你想创建丢失的目录。在

  • ^{}适用于python2和{}:

    ^{2美元
  • 我更喜欢使用^{},但它只在python3.4之后才可用:

    for fname in files:
        path = pathlib.Path(matplotlib.get_configdir(), fname)
        path.parent.mkdir(parents=True, exist_ok=True)
    

相关问题 更多 >