将management.call_command()标准输出重定向到文件 [英] Redirect management.call_command() stdout to a file
问题描述
我一直在尝试使用以下代码重定向自定义django命令的标准输出:
I've been trying to redirect the standard output of a custom django command using this piece of code:
from django.core.management.base import BaseCommand
from django.core import management
class Command(BaseCommand):
def handle(self, *args, **options):
f = open('/tmp/output', 'r+')
management.call_command('basequery', 'list', 'log', stdout=f)
f.close()
但是,当我从manage.py调用此标准输出时出现在控制台上,并且/ tmp / output文件已创建但为空。
However, when I call this from manage.py the standard output appears on the console and the /tmp/output file is created but empty.
这是django 文档
Here's the django documentation of what I'm trying to do
推荐答案
您的命令可能只是直接使用 print
。为了能够在管理命令中捕获或重定向打印,您需要使用命令实例的 self.stdout
句柄:
Your command is probably just using print
directly. To be able to capture or redirect prints in a management command, you'll want to use the self.stdout
handle of the command instance:
from __future__ import print_function
class Command(BaseCommand):
def handle(self, *args, **options):
# incorrect way to print in a management command:
print('This line will go to the terminal')
# correct ways to print in a management command:
print('This line will go into the StringIO', file=self.stdout)
self.stdout.write('This will also go into the StringIO')
如果您绝对不能更改命令的错误打印语句(这是'basequery中的代码'
命令在您的示例中出错),那么您可以使用上下文管理器临时重定向标准输出,以捕获该输出。重定向后还原旧的标准输出很重要。参见 contextlib.redirect_stdout
。
If you absolutely can not change the buggy print statements of the command (it's the code in 'basequery'
command at fault in your example), then you can use a context manager to temporarily redirect stdout in order to capture that output. It's important to restore the old stdout after redirection. See contextlib.redirect_stdout
.
这篇关于将management.call_command()标准输出重定向到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!