2012-04-20 101 views
2

我想運行一個類似這樣的命令,但函數handle (self,*args,**options)似乎沒有執行嵌套函數。創建django管理命令

如何在handle()中包含我的功能?

from django.core.management.base import NoArgsCommand 

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

必須 '叫'爲了執行它們的定義之後的函數:hello(); hello1() – Don 2012-04-20 08:56:38

回答

3

您也可以 '隨時' 定義功能:

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() 
+0

:嘿感謝了很多..它真的幫助....一個更多的疑問....如果我想調用一個函數,從命令行參數,然後我應該怎麼做?我是否必須使用class Command或其他類。 – 2012-04-24 05:03:54

+0

是的,你必須擴展BaseCommand並使用'handle'方法。請參閱此處(https://docs.djangoproject.com/en/dev/howto/custom-management-commands)有兩種參數:「* args」或「option_list」 – Don 2012-04-24 06:17:02