问题:如何从Django Shell执行Python脚本?
我需要从Django Shell执行Python脚本。我试过了:
./manage.py shell << my_script.py
但这没有用。只是在等我写东西。
I need to execute a Python script from the Django shell. I tried:
./manage.py shell << my_script.py
But it didn’t work. It was just waiting for me to write something.
回答 0
该<<
部分有误,请<
改用:
$ ./manage.py shell < myscript.py
您也可以这样做:
$ ./manage.py shell
...
>>> execfile('myscript.py')
对于python3,您需要使用
>>> exec(open('myscript.py').read())
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
>>> exec(open('myscript.py').read())
回答 1
你不建议这样做,从shell
-这是为了你真不该从Django的环境中执行随机脚本(但也有是解决这个办法,看到其他的答案)。
如果您要多次运行该脚本,则最好将其设置为自定义命令,即
$ ./manage.py my_command
要做到这一点创建一个子目录文件management
和commands
你的app
,即
my_app/
__init__.py
models.py
management/
__init__.py
commands/
__init__.py
my_command.py
tests.py
views.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
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).
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
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
)
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
回答 2
对于使用Django 1.7+的任何人,似乎仅仅导入settings模块是不够的。
经过一番挖掘,我找到了这个堆栈溢出的答案:https : //stackoverflow.com/a/23241093
您现在需要:
import os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
django.setup()
# now your code can go here...
没有执行上述操作,我得到了一个django.core.exceptions.AppRegistryNoReady
错误。
我的脚本文件与django项目位于同一目录(即,与manage.py位于同一文件夹)
For anyone using Django 1.7+, it seems that simply import the settings module is not enough.
After some digging, I found this Stack Overflow answer: 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.
My script file is in the same directory as my django project (ie. in the same folder as manage.py)
回答 3
我参加聚会很晚,但希望我的回复对某人有帮助:您可以在Python脚本中执行以下操作:
import sys, os
sys.path.append('/path/to/your/django/app')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings
其余的东西都在这里….
I’m late for the party but I hope that my response will help someone: You can do this in your Python script:
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 ….
回答 4
回答 5
如果IPython可用(pip install ipython
),./manage.py shell
它将自动使用它的外壳,然后可以使用magic命令%run
:
%run my_script.py
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
:
%run my_script.py
回答 6
您可以仅在DJANGO_SETTINGS_MODULE
设置了环境变量的情况下运行脚本。这就是设置Django-shell环境所需的全部。
这适用于Django> = 1.4
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.
This works in Django >= 1.4
回答 7
@AtulVarma在无法接受的答案下提供了非常有用的评论:
echo 'import myscript' | python manage.py shell
@AtulVarma provided a very useful comment under the not-working accepted answer:
echo 'import myscript' | python manage.py shell
回答 8
如果脚本中没有很多命令,请使用它:
manage.py shell --command="import django; print(django.__version__)"
Django文档
if you have not a lot commands in your script use it:
manage.py shell --command="import django; print(django.__version__)"
Django docs
回答 9
正如其他答案指出但未明确指出的那样,您实际需要的不一定是从Django Shell执行脚本,而是在不使用Django Shell的情况下访问应用程序。
Django版本与Django版本有很大不同。如果在该线程上找不到解决方案,请在此处回答 -Django脚本无需使用manage.py shell即可访问模型对象 -或类似的搜索可能会对您有所帮助。
我必须以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
然后跑 python3 my_command.py
(Django 2.0.2)
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.
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.
I had to begin my_command.py with
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
(Django 2.0.2)
回答 10
import os, sys, django
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
sys.path.insert(0, os.getcwd())
django.setup()
import os, sys, django
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
sys.path.insert(0, os.getcwd())
django.setup()
回答 11
请注意,此方法已被django的最新版本淘汰!(> 1.3)
一个替代答案,您可以将其添加到 my_script.py
from django.core.management import setup_environ
import settings
setup_environ(settings)
并my_script.py
仅在您所在的目录中使用python 执行,settings.py
但这有点麻烦。
$ python my_script.py
Note, this method has been deprecated for more recent versions of django! (> 1.3)
An alternative answer, you could add this to the top of 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.
$ python my_script.py
回答 12
如果您想更好地在BG中运行:
nohup echo 'exec(open("my_script.py").read())' | python manage.py shell &
输出将在 nohup.out
If you want to run in in BG even better:
nohup echo 'exec(open("my_script.py").read())' | python manage.py shell &
The output will be in nohup.out
回答 13
回答 14
如果您使用的是虚拟环境,请尝试以下操作:
python manage.py shell
要使用这些命令,您必须位于虚拟环境中。为此用途:
工作vir_env_name
例如 :-
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)
>>>
注意:-这里的mysite是我的网站名称,而jango是我的虚拟环境名称
Try this if you are using virtual enviroment :-
python manage.py shell
for using those command you must be inside virtual enviroment. for this use :-
workon 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
回答 15
来到这里的是与OP相同的问题,我发现我最喜欢的答案恰好是问题中的错误,这在Python 3中也适用:
./manage.py shell <<EOF
import my_script
my_script.main()
EOF
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:
./manage.py shell <<EOF
import my_script
my_script.main()
EOF
回答 16
另一种执行此方法的方法:
echo 'execfile("/path_to/myscript.py")' | python manage.py shell --settings=config.base
这适用于Python2.7和Django1.9
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
回答 17
如果要执行启动脚本(例如,导入一些django模型以交互方式使用它们)并保留在django shell中:
PYTHONSTARTUP=my_script.py python manage.py shell
If you want to execute startup script (e.g. import some django models to work with them interactively) and remain in django shell:
PYTHONSTARTUP=my_script.py python manage.py shell
回答 18
django shell是在django环境中执行python模块的好方法,但是手动导入模块和执行函数并不总是那么容易且麻烦,尤其是在没有自动完成的情况下。为了解决这个问题,我创建了一个小的shell脚本“ runscript.sh”,使您可以充分利用Linux控制台的自动完成功能和日志历史记录。
注意:将runscript.sh复制到根项目并设置执行权限(chmod + x)
例如:我想在myapp / do_folder /中的do_somethings.py模块中运行名为show(a,b,c)的python函数。
django的标准方式(manage.py shell):
python3 manage.py shell
> from myapp.do_folder import do_somethings
> do_somethings.show("p1", "p2" , 3.14159)
使用脚本(runscript.sh):
./runscript.sh myapp/do_folder/do_somethings.py show p1 p2 3.14159
脚本的参数数量不受限制。但是,仅支持基本类型的参数(int,float,string)
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. 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.
NB: Copy runscript.sh to the root project and set the execute right (chmod +x)
For example: I want to run python function named show(a, b, c) in module do_somethings.py in myapp/do_folder/
The standard django way (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 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)
回答 19
晚会。但这可能对某人有用。
您只需要脚本并django-extensions
安装。
只需运行shell_plus
可用的django_extensions
并导入您编写的脚本即可。
如果脚本scpt.py
位于文件夹中fol
,则可以按以下方式运行脚本。
python manage.py shell_plus
并按如下所示将您的脚本导入外壳。
>>> from fol import scpt
Late to the party. But this might be helpful for someone.
All you need is your script and django-extensions
installed.
Just run the shell_plus
available in django_extensions
and import the script that you’ve written.
If your script is scpt.py
and it’s inside a folder fol
you can run the script as follows.
python manage.py shell_plus
and just import your script inside the shell as follows.
>>> from fol import scpt
回答 20
django.setup()似乎不起作用。
似乎也不是必需的。
仅此而已。
import os, django, glob, sys, shelve
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myProject.settings")
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")
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。