简体   繁体   English

如何从 Django shell 执行 Python 脚本?

[英]How to execute a Python script from the Django shell?

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.它只是在等我写点什么。

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())

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如果这是一个您将多次运行的脚本,最好将其设置为自定义命令,

 $ ./manage.py my_command

to do this create a file in a subdir of management and commands of your app , ie为此,请在您的appmanagementcommands的子目录中创建一个文件,即

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

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.AppRegistryNoReady error.没有执行上述操作,我收到了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 位于同一文件夹中)

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 ....你剩下的东西都放在这里......

runscript from django-extensions来自django-extensions 的运行runscript

python manage.py runscript scripty.py

A sample script.py to test it out:一个示例script.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-extensions 1.6.7 上测试。

如果IPython可用( pip install ipython ),那么./manage.py shell将自动使用它的 shell,然后你可以使用魔法命令%run

%run my_script.py

You can just run the script with the DJANGO_SETTINGS_MODULE environment variable set.您可以使用DJANGO_SETTINGS_MODULE环境变量集运行脚本。 That's all it takes to set up Django-shell environment.这就是设置 Django-shell 环境所需的全部内容。

This works in Django >= 1.4这适用于 Django >= 1.4

if you have not a lot commands in your script use it:如果您的脚本中没有很多命令,请使用它:

manage.py shell --command="import django; print(django.__version__)"

Django docs Django 文档

@AtulVarma 在不工作的接受答案下提供了非常有用的评论:

echo 'import myscript' | python manage.py shell

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.这与 Django 版本有很大不同。 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 脚本无需使用 manage.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)

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

django.setup()

I'm late for the party but I hope that my response will help someone: You can do this in your Python script:我参加聚会迟到了,但我希望我的回答对某人有所帮助:您可以在 Python 脚本中执行此操作:

step1: Import第一步:导入

import mysite.asgi

step2: Need to execute a Python script simply typing:步骤 2:需要执行 Python 脚本,只需键入:

python test.py

Where test.py file like look this: test.py文件看起来像这样:

import mysite.asgi

from polls.models import GMD_TABLE
print ( [obj.gt_GMD_name for obj in GMD_TABLE.objects.all()] )

FINALY: The result will be:最后:结果将是:

['ISHWARDI', 'JHENAIDHA', 'HVDC CIRCLE']

Where ['ISHWARDI', 'JHENAIDHA', 'HVDC CIRCLE'] is the values of GMD_TABLE其中['ISHWARDI', 'JHENAIDHA', 'HVDC CIRCLE']是 GMD_TABLE 的值

Note, this method has been deprecated for more recent versions of django!请注意,此方法已在较新版本的 django 中弃用! (> 1.3) (> 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.并在您拥有settings.py的目录中使用 python 执行my_script.py但这有点hacky。

$ python my_script.py

You can simply run:你可以简单地运行:

python manage.py shell < your_script.py

It should do the job!它应该做的工作!

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输出将在nohup.out

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.我刚刚发现有趣的是 Django Scripts,它允许您编写脚本以使用 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可以在此处找到有关实施和结构的更多详细信息, http: //django-extensions.readthedocs.org/en/latest/index.html

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")

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 是我的虚拟环境名称

came here with the same question as the OP, and I found my favourite answer precisely in the mistake within the question, which works also in Python 3:带着与 OP 相同的问题来到这里,我在问题中的错误中找到了我最喜欢的答案,这也适用于 Python 3:

./manage.py shell <<EOF
import my_script
my_script.main()
EOF

Other way it's execute this one:另一种方式是执行这个:

echo 'execfile("/path_to/myscript.py")' | python manage.py shell --settings=config.base

This is working on Python2.7 and Django1.9这适用于 Python2.7 和 Django1.9

如果您想执行启动脚本(例如,导入一些 django 模型以交互方式使用它们)并保留在 django shell 中:

PYTHONSTARTUP=my_script.py python manage.py shell

The django shell is the good way to execute a python module with the django environment, but it is not always easy and tiresome to import modules and execute functions manually especially without auto-completion. django shell 是在 django 环境下执行 python 模块的好方法,但手动导入模块和执行函数并不总是容易和烦人,尤其是在没有自动完成的情况下。 To resolve this, I created a small shell script "runscript.sh" that allows you to take full advantage of the auto-completion and the log history of the Linux console.为了解决这个问题,我创建了一个小的 shell 脚本“runscript.sh” ,它允许您充分利用 Linux 控制台的自动完成和日志历史记录。

NB: Copy runscript.sh to the root project and set the execute right (chmod +x)注意:将runscript.sh复制到根项目并设置执行权限(chmod +x)

For example: I want to run python function named show(a, b, c) in module do_somethings.py in myapp/do_folder/例如:我想在 myapp/do_folder/ 中的模块 do_somethings.py 中运行名为 show(a, b, c) 的 python 函数

The standard django way (manage.py shell):标准的django方式(manage.py shell):

python3 manage.py shell
 > from myapp.do_folder import do_somethings
 > do_somethings.show("p1", "p2"  , 3.14159)

With script (runscript.sh):使用脚本(runscript.sh):

./runscript.sh myapp/do_folder/do_somethings.py show p1 p2 3.14159

The script is not limited in number of arguments.该脚本的参数数量不受限制。 However only arguments of primitive types are supported (int, float, string)但是只支持原始类型的参数(int、float、string)

Late to the party.聚会迟到了。 But this might be helpful for someone.但这可能对某人有帮助。

All you need is your script and django-extensions installed.您只需要安装脚本和django-extensions

Just run the shell_plus available in django_extensions and import the script that you've written.只需运行shell_plus可用的django_extensions并导入您编写的脚本。

If your script is scpt.py and it's inside a folder fol you can run the script as follows.如果你的脚本是scpt.py ,这是一个文件夹内fol您可以按以下方式运行的脚本。

python manage.py shell_plus

and just import your script inside the shell as follows.并按如下方式在 shell 中导入您的脚本。

>>> from fol import scpt

First check your file.首先检查你的文件。

py manage.py

If your file is shown如果显示您的文件

[contracts]
category_load

Now you can run your .py file by typing in the powershell(terminal)现在您可以通过键入 powershell(terminal) 来运行您的 .py 文件

py manage.py category_load

Actually it is very simple, once you open django shell with python manage.py shell其实很简单,打开 django shell 和python manage.py shell
then simply write然后简单地写
import test
to import test.py导入测试.py

# test.py
def x():
  print('hello');

Now you can execute the commands in this file as现在您可以执行此文件中的命令

test.x() //  will print hello

put globals().update(locals()) after importing statement在导入语句之后放置globals().update(locals())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM