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

时间:2022-04-30 13:55:35

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'仍然是none:目的:检查不是由django创建的旧数据库中的现有表

1 个解决方案

#1


10  

You have to redirect call_command's output, otherwise it just prints to stdout but returns nothing. You could try saving it to a file, then reading it in like this:

你必须重定向call_command的输出,否则它只是打印到stdout但没有返回任何内容。您可以尝试将其保存到文件中,然后像这样读取它:

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. Here's an example from one of Django's test suites:

编辑:几年后看看这个,更好的解决方案是创建一个StringIO来重定向输出,而不是真正的文件。以下是Django测试套件中的一个示例:

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

#1


10  

You have to redirect call_command's output, otherwise it just prints to stdout but returns nothing. You could try saving it to a file, then reading it in like this:

你必须重定向call_command的输出,否则它只是打印到stdout但没有返回任何内容。您可以尝试将其保存到文件中,然后像这样读取它:

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. Here's an example from one of Django's test suites:

编辑:几年后看看这个,更好的解决方案是创建一个StringIO来重定向输出,而不是真正的文件。以下是Django测试套件中的一个示例:

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