2012-04-24 77 views
2

我想传递参数以及此管理命令。我命令列运行该代码为django管理命令:使用LabelCommand

python manage.py example1 amita 

其中例1是我的文件的名称,阿弥陀佛的说法。上运行此我得到error.i正在粘贴回溯:

Traceback (most recent call last): 


File "manage.py", line 79, in <module> 
    execute_manager(settings) 
    File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 438, in execute_manager 
    utility.execute() 
    File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 379, in execute 
    self.fetch_command(subcommand).run_from_argv(self.argv) 
    File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 261, in fetch_command 
    klass = load_command_class(app_name, subcommand) 
    File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 68, in load_command_class 
    return module.Command() 
AttributeError: 'module' object has no attribute 'Command' 

为example1.py的代码如下

from django.core.management.base import LabelCommand 
from django.core.management.base import BaseCommand 


def hello(name): 
    print name 

def hello1(name): 
    print name 


class LabelCommand(BaseCommand): 
    """ 
    A management command which takes one or more arbitrary arguments 
    (labels) on the command line, and does something with each of 
    them. 

    Rather than implementing ``handle()``, subclasses must implement 
    ``handle_label()``, which will be called once for each label. 

    If the arguments should be names of installed applications, use 
    ``AppCommand`` instead. 

    """ 
    args = '<label label ...>' 
    label = 'label' 

    def handle(self, *labels, **options): 
     if not labels: 
      raise CommandError('Enter at least one %s.' % self.label) 

    output = [] 
    for label in labels: 
     label_output = self.handle_label(label, **options) 
     if label_output: 
      output.append(label_output) 
    return '\n'.join(output) 



    def handle_label(self, label, **options): 
     """ 
     Perform the command's actions for ``label``, which will be the 
     string as given on the command line. 

     """ 
     hello(label) 
     hello1(label) 
     raise NotImplementedError() 
+0

句柄应该是LabelCommand类 – mossplix 2012-04-24 09:12:29

+0

中的一个方法:http://stackoverflow.com/questions/34842191/django-using-labelcommand-with-options你会发现LabelCommand是如何实现的... – nisevi 2016-05-03 13:11:44

回答

2

Django中已经有,你应该使用LabelCommand类:

from django.core.management.base import LabelCommand 

然后您只需重写handle_label命令。