自定义 django-admin 命令 - AttributeError:“Command”对象没有属性“stdout”

2024-04-27

以下是编写自定义 django-admin 命令的示例here http://docs.djangoproject.com/en/dev/howto/custom-management-commands/,我创建了以下自定义命令:

from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
    args = ''
    help = 'Test command'

    def handle(self, *args, **options):
        self.stdout.write("Hello World!")

令人惊讶的是,我收到以下堆栈跟踪:

Traceback (most recent call last):
  File "D:\My Documents\Dev\MyProject\svn\trunk\dj_project\manage.py", line 11, in <module>
    execute_manager(settings)
  File "C:\Python26\lib\site-packages\django\core\management\__init__.py", line 438, in execute_manager
    utility.execute()
  File "C:\Python26\lib\site-packages\django\core\management\__init__.py", line 379, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python26\lib\site-packages\django\core\management\base.py", line 191, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "C:\Python26\lib\site-packages\django\core\management\base.py", line 218, in execute
    output = self.handle(*args, **options)
  File "D:\My Documents\Dev\MyProject\svn\trunk\dj_project\..\dj_project\dj_app\management\commands\mytest.py", line 8, in handle
    self.stdout.write("Hello World!")
AttributeError: 'Command' object has no attribute 'stdout'

怎么会?这是一个非常基本的自定义命令,据我所知,它符合示例。

我正在使用 django 1.2.1


由于这是 Google 上的第一次点击,我将使用相同的错误消息为另一个问题编写另一个解决方案: 如果您的类 Command 实现了 __init__,它必须调用超类的 __init__。

这将起作用:

from django.core.management.base import BaseCommand

class Command(BaseCommand):

    def __init__(self, *args, **kwargs):
        super(Command, self).__init__(*args, **kwargs)
        ... do stuff

这是行不通的:

from django.core.management.base import BaseCommand

class Command(BaseCommand):

    def __init__(self, *args, **kwargs):
       ... do stuff
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

自定义 django-admin 命令 - AttributeError:“Command”对象没有属性“stdout” 的相关文章

随机推荐