使用 django:从“python manage.py shell”到 python 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4847469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:49:56  来源:igfitidea点击:

use django: from "python manage.py shell" to python script

pythondjango

提问by john

I can move to a python project directory (say c:\www\myproject) and then issue

我可以移动到 python 项目目录(比如 c:\www\myproject)然后发出

   python manage.py shell

and then I can use all modules from django project, say the following piece of commands from the shell command:

然后我可以使用 django 项目中的所有模块,从 shell 命令说以下命令:

import settings 
from django.template import Template, Context

t=Template("My name is {myname}.")
c=Context({"myname":"John"})
f = open('write_test.txt', 'w')
f.write(t.render(c))
f.close

now, when I tried to collect all my commands into a python script, say "mytest.py", I cannot execute the script. I must missed something important.

现在,当我尝试将所有命令收集到 python 脚本中时,例如“mytest.py”,我无法执行该脚本。我一定错过了一些重要的事情。

I issued python mytest.py

我发布了 python mytest.py

then I got Import error: could not import settingsIs it on sys path?"

然后我得到了Import error: could not import settings它在 sys 路径上吗?”

I'm in the project directory where settings.py resides.....

我在settings.py所在的项目目录中.....

Could some one help me out?

有人可以帮我吗?

thanks.

谢谢。

采纳答案by Marcus Whybrow

Try using a Django management commandinstead.

尝试改用Django 管理命令

# myproject/myapp/management/commands/my_command.py

from django.core.management.base import NoArgsCommand
from django.template import Template, Context
from django.conf import settings

class Command(NoArgsCommand):
    def handle_noargs(self, **options):
        t=Template("My name is {myname}.")
        c=Context({"myname":"John"})
        f = open('write_test.txt', 'w')
        f.write(t.render(c))
        f.close

And then (if you follow the docs) you will be able to execute the command in the following fashion:

然后(如果您遵循文档)您将能够以下列方式执行命令:

python manage.py my_command

回答by Marcus Whybrow

To import Django's settings use:

要导入 Django 的设置,请使用:

from django.conf import settings

回答by adieu

Try put these two lines at the beginning of your script:

尝试将这两行放在脚本的开头:

from django.conf import settings
settings.configure() # check django source for more detail

# now you can import other django modules
from django.template import Template, Context

回答by phunehehe

This method is deprecatedin Django 1.4. Use django.conf.settings.configure()instead (see @adiew's answer for example code).

此方法在 Django 1.4 中已弃用。使用django.conf.settings.configure()替代(见@ adiew对示例代码的答案)。

Old method follows.

旧方法如下。

Put this at the beginning of your script

把它放在你的脚本的开头

from django.core.management import setup_environ
import settings
setup_environ(settings)

This is really what the manage.py does behind the scene. To see it view the Django source in django/core/management/__init__.py. After executing these lines everything should be just like in ./manage.py shell.

这确实是 manage.py 在幕后所做的。要查看它,请查看django/core/management/__init__.py. 执行这些行后,一切都应该就像在./manage.py shell.

回答by James Sullivan

Instead of manually adding things to your python script, or having to fit in the management command format, in case this is not something that needs to stay around long, you can get all the benefits of the Django environment by running your script with ./manage.py runscript <myscript.py>

无需手动将内容添加到您的 python 脚本,或者必须适应管理命令格式,如果这不是需要长时间保留的内容,您可以通过运行您的脚本来获得 Django 环境的所有好处 ./manage.py runscript <myscript.py>

... but if your script is in your project folder, then you can just add this line to the top of the python script: import os; os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

...但如果您的脚本在您的项目文件夹中,那么您只需将此行添加到 python 脚本的顶部: import os; os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

回答by Babu

UPDATE:From another post.

更新:来自另一篇文章

./manage.py shell < myscript.py

./manage.py shell < myscript.py

回答by eule

Saw in https://stackoverflow.com/a/24456404/4200284a good solution for Django >= 1.7and in case someone uses django-configurationsthis worked for me:

https://stackoverflow.com/a/24456404/4200284 中看到Django >= 1.7 的一个很好的解决方案,如果有人使用django-configurations,这对我有用:

import sys, os, django

sys.path.append('/path/to/project')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.local") # path to config

## if using django-configurations
os.environ.setdefault("DJANGO_CONFIGURATION", "Local")
from configurations import importer
importer.install()

django.setup() ## apparently important for django 1.7

from foo.models import Bar

print Bar.objects.all()

回答by Luc Saffre

Here is yet another variant: I wrote and often use a management command "run" which has the advantage that scripts can see their command-line parameters:

这是另一个变体:我编写并经常使用管理命令“run”,它的优点是脚本可以看到它们的命令行参数:

http://lino-framework.org/api/lino.management.commands.run.html

http://lino-framework.org/api/lino.management.commands.run.html