Skip to main content
 首页 » 编程设计

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

2025年05月04日10birdshome

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

具体来说,我想要:

  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 
)