如何从 Django shell 执行 Python 脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16853649/
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 23:49:04  来源:igfitidea点击:

How to execute a Python script from the Django shell?

pythondjangodjango-shell

提问by

I need to execute a Python script from the Django shell. I tried:

我需要从 Django shell 执行 Python 脚本。我试过:

./manage.py shell << my_script.py

But it didn't work. It was just waiting for me to write something.

但它没有用。只是等着我写点什么。

采纳答案by codeape

The <<part is wrong, use <instead:

<<部分是错误的,使用<来代替:

$ ./manage.py shell < myscript.py

You could also do:

你也可以这样做:

$ ./manage.py shell
...
>>> execfile('myscript.py')

For python3 you would need to use

对于python3,您需要使用

>>> exec(open('myscript.py').read())

回答by danodonovan

You're not recommended to do that from the shell- and this is intended as you shouldn't really be executing random scripts from the django environment (but there areways around this, see the other answers).

你不建议这样做,从shell-这是为了你真不该从Django的环境中执行随机脚本(但也有解决这个办法,看到其他的答案)。

If this is a script that you will be running multiple times, it's a good idea to set it up as a custom commandie

如果这是一个您将多次运行的脚本,最好将其设置为自定义命令,

 $ ./manage.py my_command

to do this create a file in a subdir of managementand commandsof your app, ie

为此,请在您的managementcommands的子目录中创建一个文件app,即

my_app/
    __init__.py
    models.py
    management/
        __init__.py
        commands/
            __init__.py
            my_command.py
    tests.py
    views.py

and in this file define your custom command (ensuring that the name of the file is the name of the command you want to execute from ./manage.py)

并在此文件中定义您的自定义命令(确保文件名是您要从中执行的命令的名称./manage.py

from django.core.management.base import BaseCommand

class Command(BaseCommand):
    def handle(self, **options):
        # now do the things that you want with your models here

回答by danodonovan

Note, this method has been deprecated for more recent versions of django!(> 1.3)

请注意,此方法已在较新版本的 django 中弃用!(> 1.3)

An alternative answer, you could add this to the top of my_script.py

另一个答案,您可以将此添加到顶部 my_script.py

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

and execute my_script.pyjust with python in the directory where you have settings.pybut this is a bit hacky.

my_script.py在您拥有的目录中仅使用 python执行,settings.py但这有点hacky。

$ python my_script.py

回答by Vlastimil Zíma

You can just run the script with the DJANGO_SETTINGS_MODULEenvironment variable set. That's all it takes to set up Django-shell environment.

您可以使用DJANGO_SETTINGS_MODULE环境变量集运行脚本。这就是设置 Django-shell 环境所需的全部内容。

This works in Django >= 1.4

这适用于 Django >= 1.4

回答by e-nouri

I'm late for the party but I hope that my response will help someone: You can do this in your Python script:

我参加聚会迟到了,但我希望我的回答对某人有所帮助:您可以在 Python 脚本中执行此操作:

import sys, os
sys.path.append('/path/to/your/django/app')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings

the rest of your stuff goes here ....

你剩下的东西都放在这里......

回答by tseboho

Something I just found to be interesting is Django Scripts, which allows you to write scripts to be run with python manage.py runscript foobar. More detailed information on implementation and scructure can be found here, http://django-extensions.readthedocs.org/en/latest/index.html

我刚刚发现有趣的是 Django Scripts,它允许您编写脚本以使用 python manage.py runscript foobar 运行。可以在此处找到有关实施和结构的更多详细信息,http://django-extensions.readthedocs.org/en/latest/index.html

回答by cgons

For anyone using Django 1.7+, it seems that simply import the settings module is not enough.

对于任何使用 Django 1.7+ 的人来说,似乎仅仅导入设置模块是不够的。

After some digging, I found this Stack Overflow answer: https://stackoverflow.com/a/23241093

经过一番挖掘,我找到了这个 Stack Overflow 答案:https: //stackoverflow.com/a/23241093

You now need to:

您现在需要:

import os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
django.setup()
# now your code can go here...

Without doing the above, I was getting a django.core.exceptions.AppRegistryNoReadyerror.

如果没有执行上述操作,我就会收到django.core.exceptions.AppRegistryNoReady错误消息。

My script file is in the same directory as my django project (ie. in the same folder as manage.py)

我的脚本文件与我的 django 项目位于同一目录中(即与 manage.py 位于同一文件夹中)

回答by davidj411

django.setup() does not seem to work.

django.setup() 似乎不起作用。

does not seem to be required either.

似乎也不需要。

this alone worked.

仅此一项就奏效了。

import os, django, glob, sys, shelve
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myProject.settings")

回答by Rahul Satal

Try this if you are using virtual enviroment :-

如果您使用的是虚拟环境,请尝试此操作:-

python manage.py shell

python manage.py shell

for using those command you must be inside virtual enviroment. for this use :-

要使用这些命令,您必须在虚拟环境中。用于此用途:-

workon vir_env_name

处理 vir_env_name

for example :-

例如 :-

dc@dc-comp-4:~/mysite$ workon jango
(jango)dc@dc-comp-4:~/mysite$ python manage.py shell
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> 

Note:- Here mysite is my website name and jango is my virtual enviroment name

注意:-这里 m​​ysite 是我的网站名称,jango 是我的虚拟环境名称

回答by user5121699

import os, sys, django
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
sys.path.insert(0, os.getcwd())

django.setup()