在 setup.py 中的 pip 安装期间获取文件路径

Get file path during pip install in setup.py

我跟着mertyildiran's top answersetup.py写了一个post安装脚本:

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

here = os.path.abspath(os.path.dirname(__file__))

class PostDevelopCommand(develop):
    """Post-installation for development mode."""
    def run(self):
        file = os.path.join(here, 'TESTFILE')
        print(file) # /path/to/my/package/TESTFILE
        with open(file, 'a') as file:
            file.write('This is development.')
        develop.run(self)

class PostInstallCommand(install):
    """Post-installation for installation mode."""
    def run(self):
        file = os.path.join(here, 'TESTFILE')
        print(file) # /tmp/pip-req-build-*/TESTFILE
        with open(file, 'a') as file:
            file.write('This is Sparta!')    
        install.run(self)

setup(
    ..
    cmdclass={
        'install': PostInstallCommand,
        'develop': PostDevelopCommand,
    },
)

..但只有当我 pip install -e . 时,我才会在测试文件中获得输出。当我尝试 pip install . 时,没有任何内容写入我想要的输出文件,因为文件路径更改为 /tmp/pip-req-build-*

如何在安装前获取包目录的路径?

pipbuilds a wheel right away。这包括作为中间步骤安装到临时目录。所以所有不符合包装条件的东西都会丢失。

虽然可编辑安装just runs setup.py develop