如何使用 call_command 执行 Django 的 `syncdb --noinput` ?

发布于 2024-12-02 17:59:32 字数 494 浏览 6 评论 0原文

>>> from django.core.management import call_command
>>> call_command('syncdb')

从 python 脚本中执行syncdb管理命令。但是,我想

$ python manage.py syncdb --noinput

在 python shell 或脚本中运行等效的命令。我怎样才能做到这一点?

以下几行不会在不询问我是否要创建超级用户的情况下打断我。

>>> call_command('syncdb', noinput = True) # asks for input
>>> call_command('syncdb', 'noinput') # raises an exception

我使用 Django 1.3。

>>> from django.core.management import call_command
>>> call_command('syncdb')

executes the syncdb management command from within a python script. However, I want to run the equivalent of

$ python manage.py syncdb --noinput

from within a python shell or script. How can I do that?

The following lines don't work without interrupting me with the question whether I want to create a super user.

>>> call_command('syncdb', noinput = True) # asks for input
>>> call_command('syncdb', 'noinput') # raises an exception

I use Django 1.3.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

贵在坚持 2024-12-09 17:59:32
call_command('syncdb', interactive = False)

编辑:

我在源代码中找到了答案。所有管理命令的源代码都可以在名为 management/commands/(command_name).py 的 python 模块中找到

syncdb 命令所在的 python 模块是 django.core.management.commands.syncdb

要查找该命令的源代码,您可以执行以下操作:

(env)$ ./manage.py shell
>>> from django.core.management.commands import syncdb
>>> syncdb.__file__
'/home/user/env/local/lib/python2.7/site-packages/django/core/management/commands/syncdb.pyc'
>>> 

当然,检查syncdb.py 的内容,而不是syncdb.pyc 的内容。

或者查看在线源syncdb.py 脚本包含:

    make_option('--noinput', action='store_false', dest='interactive', default=True,
        help='Tells Django to NOT prompt the user for input of any kind.'),

它告诉我们,如果我们不使用命令行上的 --noinput,我们应该使用 interactive想要自动化命令call_command 函数。

call_command('syncdb', interactive = False)

EDIT:

I found the answer in the source code. The source code for all management commands can be found in a python module called management/commands/(command_name).py

The python module where the syncdb command resides is django.core.management.commands.syncdb

To find the source code of the command you can do something like this:

(env)$ ./manage.py shell
>>> from django.core.management.commands import syncdb
>>> syncdb.__file__
'/home/user/env/local/lib/python2.7/site-packages/django/core/management/commands/syncdb.pyc'
>>> 

Of course, check the contents of syncdb.py, and not syncdb.pyc.

Or looking at the online source, the syncdb.py script contains:

    make_option('--noinput', action='store_false', dest='interactive', default=True,
        help='Tells Django to NOT prompt the user for input of any kind.'),

that tells us that instead of --noinput on the command line, we should use interactive if we want to automate commands with the call_command function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文