【问题标题】:A runall command in setup.pysetup.py 中的 runall 命令
【发布时间】:2023-12-04 09:02:01
【问题描述】:

我通过扩展setuptools python 库中的命令类创建了许多自定义命令。这些命令类似于 Clean、RunTest(每个单独的类都有它们的 run(self) 方法)。 我现在创建了一个 RunAll 类,如果它也是 Command 类的子类,并且需要调用其他命令。让我展示一些我的代码,以便更清楚。

class Clean(Command):

description = 'Cleans the build'
user_options = []

def initialize_options(self):
    pass

def finalize_options(self):
    pass

def clean(self):
    print("Cleaning")

def run(self):
    self.clean()

还有一些类似的类,如 Runtests 等,它们的格式相似。 现在我创建了一个名为 RunAll 的类,它运行所有这些命令(试图模拟 ant all 命令)。所以代码是这样的。

class RunAll(Command):
"""
runs few specific commands mentioned
"""

description = 'Runs specific commands mentioned'
user_options = []

def initialize_options(self):
    pass

def finalize_options(self):
    pass

def run(self):
    # init,clean,version,build,test,dist
    Clean().clean()
    Version().printVersion()
    RunTests().runtests()
    Dist().dist()

现在当我运行 python setup.py runall 时,我收到以下错误。

  File "C:\Users\rsareen\AppData\Local\Programs\Python\Python36\lib\site-packages\setuptools\__init__.py", line 129, in setup
return distutils.core.setup(**attrs)
  File "C:\Users\rsareen\AppData\Local\Programs\Python\Python36\lib\distutils\core.py", line 148, in setup
dist.run_commands()
  File "C:\Users\rsareen\AppData\Local\Programs\Python\Python36\lib\distutils\dist.py", line 955, in run_commands
self.run_command(cmd)
  File "C:\Users\rsareen\AppData\Local\Programs\Python\Python36\lib\distutils\dist.py", line 974, in run_command
cmd_obj.run()
  File ".\setup.py", line 58, in run
Clean().clean()
TypeError: __init__() missing 1 required positional argument: 'dist'

无法获取Command类中的dist参数。

基本上我无法实例化命令。 但是当我执行python setup.py clean 时,它运行良好。

setuptools 是这样设计的,我需要更改我的设计,还是有其他方法可以做到这一点?

【问题讨论】:

    标签: python python-3.x design-patterns setuptools


    【解决方案1】:

    命令类似乎require 一个参数并将该参数存储在self.distribution 中。所以将它传递给你创建的命令类:

    Clean(self.distribution).clean()
    …
    

    或者您可以使用 run_command 按名称运行不同的命令:

    self.run_command('clean')
    …
    

    【讨论】: