使用pip install -e在setup.py中安装data_files

时间:2019-03-17 14:46:26

标签: python pip setuptools bash-completion

我正在尝试为使用Python编写的CLI工具提供一个bash完成脚本。根据{{​​3}},setup.py中的data_files正是我所需要的:

  

尽管配置package_data可以满足大多数需求,但是在某些情况下,您可能需要将数据文件放置在包之外。使用data_files指令可以执行此操作。如果您需要安装供其他程序使用的文件(可能不了解Python程序包),则该功能非常有用。

所以我这样添加了完成文件:

data_files=[
    ('/usr/share/bash-completion/completions', ['completion/dotenv']),
],

并尝试使用:

pip install -e .

在我的虚拟环境中。但是,未安装完成脚本。我是否忘记了某些内容或pip损坏了?可以找到完整的项目Python Packaging Authority

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,并且已经实施了变通方法。

在我看来python setup.py develop或(pip install -e .)与python setup.py install所运行的功能不同。 实际上,通过查看源代码,我注意到python setup.py install运行build_py

https://github.com/python/cpython/blob/master/Lib/distutils/command/build_py.py#L134 https://github.com/pypa/setuptools/blob/master/setuptools/command/build_py.py

经过几次挖掘,我选择如下重写develop命令。以下代码是python3.6:

""" SetupTool Entry Point """
import sys
from pathlib import Path
from shutil import copy2

from setuptools import find_packages, setup
from setuptools.command.develop import develop

# create os_data_files that will be used by the default install command
os_data_files = [
    (
        f"{sys.prefix}/config",  # providing absolute path, sys.prefix will be different in venv
        [
            "src/my_package/config/properties.env",
        ],
    ),        
]


def build_package_data():
    """ implement the necessary function for develop """
    for dest_dir, filenames in os_data_files:
        for filename in filenames:
            print(
                "CUSTOM SETUP.PY (build_package_data): copy %s to %s"
                % (filename, dest_dir)
            )
            copy2(filename, dest_dir)


def make_dirstruct():
    """ Set the the logging path """
    for subdir in ["config"]:
        print("CUSTOM SETUP.PY (make_dirstruct): creating %s" % subdir)
        (Path(BASE_DIR) / subdir).mkdir(parents=True, exist_ok=True)


class CustomDevelopCommand(develop):
    """ Customized setuptools install command """

    def run(self):
        develop.run(self)
        make_dirstruct()
        build_package_data()

# provide the relevant information for stackoverflow
setup(        
    package_dir={"": "src"},
    packages=find_packages("src"),
    data_files=os_data_files,                
    cmdclass={"develop": CustomDevelopCommand},
)