これは、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やbuild.pyなどのデフォルト コマンドの 1 つのソース コードを調べることです。