# -*- coding: utf-8 -*-
"""
management_command_launcher.py
Execute management commands from view functions
Would it have been better to make it a class?
If the output is not done with self.stdout.write() within the management command,
you won't get the correct results.
(If print() is used, it can't be captured)
"""
import StringIO
from django.core.management.base import CommandError
from django.utils.encoding import smart_str
def launch_management_command(command_module, *args, **options):
"""
@args
(module) command_module:
Name of the module containing the Command class.
Example:
from appname.management.commands import hoge_command
result = launch_management_command(hoge_command, ... )
"""
log_buffer = StringIO.StringIO()
command_instance = command_module.Command()
command_instance.stdout = log_buffer
command_instance.stderr = log_buffer
try:
output = command_instance.handle(*args, **options)
if output:
log_buffer.write(smart_str(output))
except CommandError as e:
log_buffer.write(smart_str(e))
log_buffer.seek(0)
return log_buffer.read()
Comments