如何从Django shell执行Python脚本?

时间:2022-05-04 04:50:57

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.

但它不工作。只是在等我写点什么。

15 个解决方案

#1


260  

The << part is wrong, use < instead:

<部分错误,使用<代替:< p>

$ ./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())

#2


166  

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 are ways 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 command ie

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

 $ ./manage.py my_command

to do this create a file in a subdir of management and commands of your app, ie

要做到这一点,可以在应用程序的管理和命令的子目录中创建一个文件。

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_noargs(self, **options):
        # now do the things that you want with your models here

#3


77  

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://*.com/a/23241093

经过一些挖掘,我找到了这个堆栈溢出答案:https://*.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.AppRegistryNoReady error.

没有做以上这些,我得到了django.core.exception。AppRegistryNoReady错误。

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

我的脚本文件位于与django项目(即django项目)相同的目录中。在与management .py相同的文件夹中)

#4


65  

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 ....

你其他的东西就在这里....

#5


16  

runscript from django-extensions

runscript从django-extensions

python manage.py runscript scripty.py

A sample script.py to test it out:

一个示例脚本。py测试:

from django.contrib.auth.models import User
print(User.objects.values())

Mentioned at: http://django-extensions.readthedocs.io/en/latest/command_extensions.html and documented at:

提到:http://django-extensions.readthedocs.io/en/latest/command_extensions。html和记录:

python manage.py runscript --help

There is a tutorial too.

还有教程。

Tested on Django 1.9.6, django-extensions 1.6.7.

测试了Django 1.9.6, Django扩展1.6.7。

#6


7  

You can just run the script with the DJANGO_SETTINGS_MODULE environment 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中有效

#7


6  

If IPython is available (pip install ipython) then ./manage.py shell will automatically use it's shell and then you can use the magic command %run:

如果IPython可用(pip安装IPython),那么./管理。py shell将自动使用它的shell,然后您可以使用魔术命令%run:

%run my_script.py

#8


3  

@AtulVarma provided a very useful comment under the not-working accepted answer:

@AtulVarma在不工作的公认答案下提供了一个非常有用的评论:

echo 'import myscript' | python manage.py shell

#9


2  

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.py just with python in the directory where you have settings.py but this is a bit hacky.

和执行my_script。py只是在有设置的目录中使用python。但是这有点陈腐。

$ python my_script.py

#10


2  

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

django.setup()

#11


1  

Try this if you are using virtual enviroment :-

如果你正在使用虚拟环境:-尝试这个

python manage.py shell

python管理。py壳

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

注意:-这里mysite是我的网站名,jango是我的虚拟环境名

#12


0  

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脚本,它允许您编写使用python管理的脚本。py runscript foobar。在这里可以找到关于实现和scructure的更详细的信息,http://django-extensions.readthedocs.org/en/latest/index.html。

#13


0  

As other answers indicate but don't explicitly state, what you may actually need is not necessarily to execute your script from the Django shell, but to access your apps without using the Django shell.

正如其他答案所示,但不明确说明的那样,您实际上可能需要的不是从Django shell执行脚本,而是在不使用Django shell的情况下访问应用程序。

This differs a lot Django version to Django version. If you do not find your solution on this thread, answers here -- Django script to access model objects without using manage.py shell -- or similar searches may help you.

这与Django版本有很大的不同。如果您在此线程中没有找到解决方案,请在这里回答——Django脚本,以访问模型对象而不使用管理。py shell——或者类似的搜索可能会对您有所帮助。

I had to begin my_command.py with

我必须启动my_command。py和

import os,sys
sys.path.append('/path/to/myproject')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.file")
import django
django.setup()

import project.app.models
#do things with my models, yay

and then ran python3 my_command.py

然后运行python3 my_command。py

(Django 2.0.2)

(Django 2.0.2)

#14


0  

If you want to run in in BG even better:

如果你想在BG表现得更好:

nohup echo 'exec(open("my_script.py").read())' | python manage.py shell &

The output will be in nohup.out

输出将在nohu .out中

#15


-2  

django.setup() does not seem to work.

设置()似乎不起作用。

does not seem to be required either.

似乎也不需要。

this alone worked.

这单独工作。

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

#1


260  

The << part is wrong, use < instead:

<部分错误,使用<代替:< p>

$ ./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())

#2


166  

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 are ways 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 command ie

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

 $ ./manage.py my_command

to do this create a file in a subdir of management and commands of your app, ie

要做到这一点,可以在应用程序的管理和命令的子目录中创建一个文件。

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_noargs(self, **options):
        # now do the things that you want with your models here

#3


77  

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://*.com/a/23241093

经过一些挖掘,我找到了这个堆栈溢出答案:https://*.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.AppRegistryNoReady error.

没有做以上这些,我得到了django.core.exception。AppRegistryNoReady错误。

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

我的脚本文件位于与django项目(即django项目)相同的目录中。在与management .py相同的文件夹中)

#4


65  

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 ....

你其他的东西就在这里....

#5


16  

runscript from django-extensions

runscript从django-extensions

python manage.py runscript scripty.py

A sample script.py to test it out:

一个示例脚本。py测试:

from django.contrib.auth.models import User
print(User.objects.values())

Mentioned at: http://django-extensions.readthedocs.io/en/latest/command_extensions.html and documented at:

提到:http://django-extensions.readthedocs.io/en/latest/command_extensions。html和记录:

python manage.py runscript --help

There is a tutorial too.

还有教程。

Tested on Django 1.9.6, django-extensions 1.6.7.

测试了Django 1.9.6, Django扩展1.6.7。

#6


7  

You can just run the script with the DJANGO_SETTINGS_MODULE environment 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中有效

#7


6  

If IPython is available (pip install ipython) then ./manage.py shell will automatically use it's shell and then you can use the magic command %run:

如果IPython可用(pip安装IPython),那么./管理。py shell将自动使用它的shell,然后您可以使用魔术命令%run:

%run my_script.py

#8


3  

@AtulVarma provided a very useful comment under the not-working accepted answer:

@AtulVarma在不工作的公认答案下提供了一个非常有用的评论:

echo 'import myscript' | python manage.py shell

#9


2  

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.py just with python in the directory where you have settings.py but this is a bit hacky.

和执行my_script。py只是在有设置的目录中使用python。但是这有点陈腐。

$ python my_script.py

#10


2  

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

django.setup()

#11


1  

Try this if you are using virtual enviroment :-

如果你正在使用虚拟环境:-尝试这个

python manage.py shell

python管理。py壳

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

注意:-这里mysite是我的网站名,jango是我的虚拟环境名

#12


0  

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脚本,它允许您编写使用python管理的脚本。py runscript foobar。在这里可以找到关于实现和scructure的更详细的信息,http://django-extensions.readthedocs.org/en/latest/index.html。

#13


0  

As other answers indicate but don't explicitly state, what you may actually need is not necessarily to execute your script from the Django shell, but to access your apps without using the Django shell.

正如其他答案所示,但不明确说明的那样,您实际上可能需要的不是从Django shell执行脚本,而是在不使用Django shell的情况下访问应用程序。

This differs a lot Django version to Django version. If you do not find your solution on this thread, answers here -- Django script to access model objects without using manage.py shell -- or similar searches may help you.

这与Django版本有很大的不同。如果您在此线程中没有找到解决方案,请在这里回答——Django脚本,以访问模型对象而不使用管理。py shell——或者类似的搜索可能会对您有所帮助。

I had to begin my_command.py with

我必须启动my_command。py和

import os,sys
sys.path.append('/path/to/myproject')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.file")
import django
django.setup()

import project.app.models
#do things with my models, yay

and then ran python3 my_command.py

然后运行python3 my_command。py

(Django 2.0.2)

(Django 2.0.2)

#14


0  

If you want to run in in BG even better:

如果你想在BG表现得更好:

nohup echo 'exec(open("my_script.py").read())' | python manage.py shell &

The output will be in nohup.out

输出将在nohu .out中

#15


-2  

django.setup() does not seem to work.

设置()似乎不起作用。

does not seem to be required either.

似乎也不需要。

this alone worked.

这单独工作。

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