python - 如何检查 setup.py 中运行的是哪个命令?

标签 python distutils setup.py

我想知道如何使 setup.py 中的某些代码以运行的命令(例如 installupload)为条件。

具体来说,我想要:

  1. 一种添加“hacks”的简单方法,例如忽略 install 中的特定文件,但没有其他命令。
  2. 推荐/规范的方式来添加 Hook ,例如在安装前运行测试。

我试过阅读 distutils documentation ,但它在细节上非常稀疏——distutils.command[.foo] 模块完全没有记录。

对于第一点,我可以像 this question 中提到的那样检查 sys.argv ,但是当运行多个命令时这不起作用,例如:

python setup.py sdist bdist upload

所以一般不适用。

最佳答案

您可以改写命令:

from distutils.command.install import install
from distutils.core import setup

def run_file(path):
    with open(path, 'r') as f:
        exec(f.read())

class myinstall(install): # subclass distutils's install command
    def finalize_options(self): # called after option parsing
        # call base class function
        install.finalize_options(self)
        # super won't work because distutils under Python 2 uses old-style classes
        # ignore a module
        self.distribution.py_modules.remove('mymodule')
    def run(self): # called to run a command
        # run tests first
        run_file('path/to/test.py')
        # ^ remember to make sure the module is in sys.path
        # run the real commands
        install.run(self)

setup(
    name='abc',
    py_modules=['mymodule'],
    cmdclass={'install': myinstall}
    # ^ override the install command
)

关于python - 如何检查 setup.py 中运行的是哪个命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24036939/

相关文章:

python - 使用 pkg_resources 获取 python 模块完整版本

python - 使用 setuptools/distutils 构建 PyInstaller exe 时,ensure_local_distutils 内部出现断言错误

python setup.py sdist 仅包括来自顶级模块的 .py 源

c++ - 将复杂的链接标志从 Makefile 传递到 setup.py

python - 是否可以从模块导入变量以便与 Selenium 一起使用?

python - Python 包是否可以依赖于另一个 Python 包的特定版本控制修订版?

python - H5PY/Numpy - 设置 numpy 数组的内部形状(适用于 h5py)

python - 使用 setuptools 创建调用外部 C 库的 cython 包

python - 如何在 python 中绘制每个具有多个值的观察结果?

python - 我可以使用 glob 模式查询数据库吗?