gpt4 book ai didi

python - 自定义 distutils 命令

转载 作者:IT老高 更新时间:2023-10-28 22:23:41 26 4
gpt4 key购买 nike

我有一个名为“example”的库,我将它安装到我的全局站点包目录中。但是,我希望能够安装两个版本,一个用于生产,一个用于测试(我有一个 Web 应用程序和其他以这种方式进行版本控制的东西)。

有没有办法指定,比如“python setup.py stage”,它不仅可以将不同的 egg 安装到站点包中,还可以将模块从“example”重命名为“example_stage”或类似的名称?

如果distutils不能做到这一点,有没有其他工具可以做到?

最佳答案

这可以通过在 setup.py 中子类化 distutils.core.Command 使用 distutils 轻松完成。

例如:

from distutils.core import setup, Command
import os, sys

class CleanCommand(Command):
description = "custom clean command that forcefully removes dist/build directories"
user_options = []
def initialize_options(self):
self.cwd = None
def finalize_options(self):
self.cwd = os.getcwd()
def run(self):
assert os.getcwd() == self.cwd, 'Must be in package root: %s' % self.cwd
os.system('rm -rf ./build ./dist')

要启用该命令,您必须在 setup() 中引用它:

setup(
# stuff omitted for conciseness.
cmdclass={
'clean': CleanCommand
}

请注意,您也可以通过这种方式覆盖内置命令,例如我使用 'clean' 所做的。 (我不喜欢内置版本如何留下 'dist' 和 'build' 目录。)

% python setup.py --help-commands | grep clean
clean custom clean command that forcefully removes dist/build dirs.

使用了许多约定:

  • 您可以使用 user_options 指定任何命令行参数。
  • 您声明将与 initialize_options() 方法一起使用的任何变量,该方法在初始化后调用以设置子类的自定义命名空间。
  • finalize_options() 方法在 run() 之前调用。
  • 命令本身的内容将在 run() 中完成,因此请务必在此之前进行任何其他准备工作。

最好的例子是查看 PYTHON_DIR/distutils/command 中的默认命令之一的源代码,例如 install.py 或 < em>build.py.

关于python - 自定义 distutils 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1710839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com