django shell_plus timeit call_command吗?

时间:2018-06-20 10:20:24

标签: django django-extensions django-commands

我写了一个django命令,想看看它的时机,所以在django shell_plus里面我这样做:

import timeit
from django.core.management import call_command

timeit.timeit("""call_command('prova')""", number=3 )

该命令应运行3次并输出其运行时间。

如果直接运行“ call_command”,它将起作用,如果在timeit内调用,则会抛出此错误:

/usr/lib/python3.5/timeit.py in timeit(self, number)
    176         gc.disable()
    177         try:
--> 178             timing = self.inner(it, self.timer)
    179         finally:
    180             if gcold:

/usr/lib/python3.5/timeit.py in inner(_it, _timer)

NameError: name 'call_command' is not defined

1 个答案:

答案 0 :(得分:1)

timeit始终在新的执行上下文中运行,它无权访问您先前导入的任何内容。您需要传递带有设置代码的单独参数:

timeit.timeit("call_command('prova')", number=3, setup='from django.core.management import call_command' )

请参见timeit docs

相关问题