【问题标题】:How to save output from django call_command to a variable or file如何将 django call_command 的输出保存到变量或文件中
【发布时间】:2014-12-20 19:41:10
【问题描述】:

我在 Django 中从类似于以下的脚本调用命令:

#!/usr/bin/python
from django.core.management import call_command
call_command('syncdb')
call_command('runserver')
call_command('inspectdb')

如何将例如 call_command('inspectdb') 的输出分配给变量或文件?

我试过了

var = call_command('inspectdb')

但“var”仍然没有:目的:检查旧数据库中不是由 django 创建的现有表

【问题讨论】:

标签: python django


【解决方案1】:

你必须重定向 call_command 的输出,否则它只会打印到标准输出但什么也不返回。您可以尝试将其保存到文件中,然后像这样读取它:

with open('/tmp/inspectdb', 'w+') as f:
    call_command('inspectdb', stdout=f)
    var = f.readlines()

编辑: 几年后看看这个,更好的解决方案是创建一个StringIO 来重定向输出,而不是一个真实的文件。 这是来自Django's test suites 之一的示例:

from io import StringIO

def test_command(self):
    out = StringIO()
    management.call_command('dance', stdout=out)
    self.assertIn("I don't feel like dancing Rock'n'Roll.\n", out.getvalue())

【讨论】:

  • 试过这个,但它似乎不起作用,在命令行上运行 inspectdb 时 var 变成一个空列表会产生推断的模型。我会尝试子进程。
  • FWIW 您可能没有使用 self.stdout.write() 在命令中执行输出。
  • 我不知道stdout=f 是如何进入使用stdout 的Command 构造函数的。 call_command 调用 load_command_class(app_name, name) 并且不传递标准输出,并且命令实例化时没有像 module.Command() 这样的参数。这是 Command 的构造函数:def __init__(self, stdout=None, stderr=None, no_color=False):
  • @Matt:stdout 参数在**options 中被捕获,转换为一个名为defaults 的字典,并作为command.execute(*args, **defaults) 传递给命令。所以你是对的,它没有传递给构造函数;请查看Command.execute
【解决方案2】:

这在“从您的代码运行管理命令 > 输出重定向”下的 Django Documentation 中记录。

要保存到变量,您可以这样做:

import io
from django.core.management import call_command


with io.StringIO() as out:
   call_command('dumpdata', stdout=out)
   print(out.getvalue())

要保存到文件,您可以这样做:

from django.core.management import call_command


with open('/path/to/command_output', 'w') as f:
    call_command('dumpdata', stdout=f)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-01
    • 2011-11-10
    • 2013-04-11
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 2021-10-10
    • 2021-11-12
    相关资源
    最近更新 更多