---
slug: "マネジメントコマンドをview関数内から実行する"
title: "Executing Management Commands from Within a View Function"
description: "```python"
url: "https://www.ytyng.com/en/blog/マネジメントコマンドをview関数内から実行する"
publish_date: "2011-06-09T01:45:52Z"
created: "2011-06-09T01:45:52Z"
updated: "2026-02-26T20:44:15.273Z"
categories: ["Django"]
keywords: ""
featured_image_url: "https://media.ytyng.com/resize/20230812/0e228dbdaf914f01b50744f618b5b757.png.webp?width=768"
has_video: false
has_music: false
video_urls: []
music_urls: []
lang: "en"
---

# Executing Management Commands from Within a View Function

```python
# -*- 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()
```
