【问题标题】:how to write multiple management commands in one file? django如何在一个文件中写入多个管理命令? django
【发布时间】:2017-06-28 18:48:29
【问题描述】:

我一直在通过阅读this阅读如何编写django管理命令。

我也阅读了 django 文档,但我想知道是否可以编写几个命令来仅使用一个文件运行?

而不是编写几个不同的文件。

【问题讨论】:

    标签: python django command


    【解决方案1】:

    我不这么认为。如果我正确读取源代码,则通过查找模块从 CLI 中发现命令:

    https://github.com/django/django/blob/master/django/core/management/init.py#L26

    收集使用:

    https://docs.python.org/2/library/pkgutil.html#pkgutil.iter_modules

    【讨论】:

    • 好吧,我阅读了文档,它清楚地指出它从定义类命令的每个模块中发现命令。完全同意dm。
    • thx thx,只是觉得可能有替代品的机会
    • 看看这个 - 我认为你可以重新设计它以满足我们的需求。真的很酷的脚本。 masnun.com/2015/09/29/…
    【解决方案2】:

    您可以在一个文件中编写多个命令。请按照以下步骤操作

    1. 在您的应用根目录下创建 ma​​nagement/init.py 文件夹
    2. 在管理目录下创建commands/init.py文件夹
    3. 在commands目录下创建mycommand.py文件
    4. 在 mycommand.py 文件中写入以下代码

    from django.core.management.base import BaseCommand
    from subprocess import Popen
    from sys import stdout, stdin, stderr
    import time
    import os
    import signal
    
    
    class Command(BaseCommand):
        help = 'Run all commands'
        commands = [
            'python manage.py schedule',
            'python manage.py runserver'
    
        ]
    
        def handle(self, *args, **options):
            proc_list = []
    
            for command in self.commands:
                print("$ " + command)
                proc = Popen(command, shell=True, stdin=stdin,
                             stdout=stdout, stderr=stderr)
                proc_list.append(proc)
    
            try:
                while True:
                    time.sleep(10)
            except KeyboardInterrupt:
                for proc in proc_list:
                    os.kill(proc.pid, signal.SIGKILL)
    1. 将您的 cmd 目录更改为您的项目根目录
    2. 运行:python manage.py mycommand

    这个link 帮助了我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-29
      • 1970-01-01
      相关资源
      最近更新 更多