【问题标题】:Creating django management commands创建 django 管理命令
【发布时间】:2012-05-01 20:07:00
【问题描述】:

我想运行一个类似这样的命令,但函数 handle (self,*args,**options) 似乎没有执行嵌套函数。

如何在handle() 中包含我的函数?

from django.core.management.base import NoArgsCommand

class Command(NoArgsCommand):
    def handle(self, *args, **options):
        def hello():
            print "hello1"
        def hello1():
            print "hello2"

【问题讨论】:

  • 您必须在函数定义之后“调用”函数才能执行它们:hello();你好1()

标签: django django-admin python-2.7


【解决方案1】:

您还可以“即时”定义函数:

class Command(NoArgsCommand):
    def handle_noargs(self):
        def hello():
            print "hello1"

        def hello1():
            print "hello2"

        hello()
        hello1()

或在命令之外(因为它们是“服务”功能的地方):

def hello():
    print "hello1"

def hello1():
    print "hello2"


class Command(NoArgsCommand):

    def handle_noargs(self):
        hello()
        hello1()

【讨论】:

  • :嘿,非常感谢.. 它真的有帮助.. 还有一个疑问.... 如果我想调用一个从命令行获取参数的函数,那么我应该怎么做这样做????.我必须使用类命令或其他类。
  • 是的,您必须扩展 BaseCommand 并使用 'handle' 方法。请参阅此处 (docs.djangoproject.com/en/dev/howto/custom-management-commands) 了解两种获取参数的方式:“*args”或“option_list”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-29
  • 1970-01-01
  • 1970-01-01
  • 2014-08-21
  • 2016-08-10
  • 2013-06-05
  • 2012-05-04
相关资源
最近更新 更多