简体   繁体   English

如何将 django call_command 的输出保存到变量或文件

[英]How to save output from django call_command to a variable or file

I am calling commands in Django from within a script similar to:我正在从类似于以下的脚本中调用 Django 中的命令:

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

How to I assign the output from for instance call_command('inspectdb') to a variable or a file?如何将例如 call_command('inspectdb') 的输出分配给变量或文件?

I've tried我试过了

var = call_command('inspectdb')

but 'var' remains none: purpose: inspect existing tables in legacy databases not created by django但“var”仍然没有:目的:检查不是由 django 创建的遗留数据库中的现有表

You have to redirect call_command's output, otherwise it just prints to stdout but returns nothing.您必须重定向 call_command 的输出,否则它只会打印到标准输出但不返回任何内容。 You could try saving it to a file, then reading it in like this:您可以尝试将其保存到文件中,然后像这样读取它:

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

EDIT: Looking at this a couple years later, a better solution would be to create a StringIO to redirect the output, instead of a real file.编辑:几年后看这个,更好的解决方案是创建一个StringIO来重定向输出,而不是一个真正的文件。 Here's an example from one of Django's test suites :这是Django 测试套件之一的示例:

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

This is documented in the Django Documentation under "Running management commands from your code > Output redirection".这在Django 文档中的“从您的代码运行管理命令 > 输出重定向”下进行了记录。

To save to a variable, you could do:要保存到变量,您可以执行以下操作:

import io
from django.core.management import call_command


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

To save to a file, you could do:要保存到文件,您可以执行以下操作:

from django.core.management import call_command


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM