【问题标题】:django shell_plus timeit call_command?django shell_plus timeit call_command?
【发布时间】:2018-06-20 10:20:24
【问题描述】:

我写了一个 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

【问题讨论】:

    标签: django django-extensions django-commands


    【解决方案1】:

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

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

    请参阅timeit docs

    【讨论】:

      猜你喜欢
      • 2019-08-03
      • 1970-01-01
      • 2017-07-27
      • 2011-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多