向setup.py里添加自定义command

setup.py里添加自定义command

参考这里

继承distutils.cmd.Command类:

class CCleanCommand(distutils.cmd.Command):
    """clean the source code and the .c file after building .so"""

    # 命令的描述,会出现在`python setup.py --help`里
    description = 'clean the source code and the .c file after building .so'
    # 该命令的所有选项,包括需要给值的选项,以及只是当个flag用的binary选项
    user_options = [
        # 格式是`(长名字,短名字,描述)`,描述同样会出现在doc里
        # binary选项,长名字后面没有等号,最后的值会传给`self.<长名字>`,使用形式`--restore`/`-r`
        ('restore', 'r', 'moving the source back to its dir'),
        # 需要值的选项,长名字后面有等号,最后的值会传给`self.<长名字>`(-会用_代替),使用形式`--key-value=<val>`/`-k <val>`
        ('key-value=', 'k', 'example for key=value option')
    ]

    def initialize_options(self):
        """设置选项的默认值, 每个选项都要有初始值,否则报错"""
        self.restore = False
        self.key_value = 123

    def finalize_options(self):
        """接收到命令行传过来的值之后的处理, 也可以什么都不干"""
        print("restore=", self.restore)
        print("key_value=", self.key_value)
        self.key_value = f'{self.key_value}'+".exe"

    def run(self):
        """命令运行时的操作"""
        print("======= command is running =======")
        if self.restore:
            print('good')
        else:
            print(self.key_value)

然后需要在setup函数里设置好:

setup(
    ...,
    cmdclass={
        'cclean': CCleanCommand
    }
)

然后就可以通过python setup.py cclean来使用了:

>>> python setup.py cclean
running cclean
restore= False
key_value= 123
======= command is running =======
123.exe

>>> python setup.py cclean -r
running cclean
restore= 1
key_value= 123
======= command is running =======
good

>>>  python setup.py cclean --restore
running cclean
restore= 1
key_value= 123
======= command is running =======
good

>>> python setup.py cclean --restore=1
报错

>>> python setup.py cclean --key-value=456
running cclean
restore= False
key_value= 456
======= command is running =======
456.exe

>>> python setup.py cclean -k 456
running cclean
restore= False
key_value= 456
======= command is running =======
456.exe

>>> python setup.py cclean -k=456
running cclean
restore= False
key_value= =456
======= command is running =======
=456.exe
posted @ 2021-03-31 22:59  milliele  阅读(436)  评论(0编辑  收藏  举报